迭代和设置Ruby对象实例变量 [英] Iterate and Set Ruby Object Instance Variables
问题描述
我正在寻找一种方法来遍历Ruby对象的实例变量,并使用通用设置器分别设置它们(从提供的哈希值中).我假设我可以直接在一个方法中遍历它们,并简单地分别设置它们.
I'm looking for a way to iterate through a Ruby object's instance variables, and set them individually (from a provided hash) using a generic setter. I am assuming I can iterate through them directly in a method and simply set each individually.
这是我的对象实例,你:
Here is my object instance, u:
u = #<Waffle:0x00007fc6b1145530
@id=nil,
@alpha="",
@bravo="",
@charlie="",
@delta=nil,
@echo=nil,
@status=new>
我想用给定的哈希h填充它:
I would like to populate it with a given hash, h:
h = {
"id"=>"141",
"alpha"=>"Muccahiya""
"bravo"=>"$2a$10$xR2g",
"charlie"=>"2018-02-21 10:41:56-05",
"delta"=>"2018-02-05 18:17:16.752606-05",
"echo"=>"wobbly",
"status"=>"active"
}
这是我拥有的方法,它会引发此错误:
This is the method I have and it is throwing this error:
def to_obj(h)
self.instance_variables.each do |i|
self.i = h[i.sub('@','')]
end
end
错误:
Traceback (most recent call last):
3: from /users/rich/app.rb:31:in `<main>'
2: from /Library/WebServer/Documents/dingbat/models/waffle.rb:240:in `to_obj'
1: from /Library/WebServer/Documents/dingbat/models/waffle.rb:240:in `each'
/Library/WebServer/Documents/dingbat/models/waffle.rb:241:in `block in to_obj': no implicit conversion of String into Integer (TypeError)
self.instance_variables
确实是一个符号数组.
self.instance_variables
is indeed an array of symbols.
我认为对象可以给定哈希值来设置其instance_variables
.这不难.
I am thinking that an object can set its instance_variables
given a hash. This can't be difficult.
推荐答案
def to_obj(h)
h.each{|k, v| instance_variable_set("@{k}", v)}
end
如果仅在定义了此类实例变量的情况下才想设置值,请执行以下操作:
If you want to set a value only if such instance variable is defined, then do:
def to_obj(h)
h.each do
|k, v|
next unless instance_variable_defined?("@{k}")
instance_variable_set("@{k}", v)
end
end
这篇关于迭代和设置Ruby对象实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!