这个问题在这里已有答案:
我试图设置实例变量而不用单个setter穿孔我的对象。我想使用我称之为组setter的方法来实现它。
我想迭代一个对象的instance_variables
,对于那些与预先提供的哈希中的键匹配的那些,使用instance_variable_set
单独设置它们。我不想迭代哈希对来限定实例变量的设置,因为这是一个安全问题。
这是我的代码:
class Pickle
attr_accessor :id, :name, :colour, :status
def initialize()
@id = nil
@name = nil
@colour = 'green'
@status = 'new'
end
def into_me(incoming)
instance_variables.each do |i|
puts i
puts incoming[i]
instance_variable_set(i, incoming[i])
end
end
end
a = Pickle.new
# >> @id
# => #<Pickle:0x00007fef6782c978 @colour="green", @id=nil, @name=nil, @status="new">
newstuff = {:name => 'Peter', :colour => 'red'}
a.into_me(newstuff)
# >> @name
# >> @colour
# >> @status
# => #<Pickle:0x00007fef6782c978 @colour=nil, @id=nil, @name=nil, @status=nil>
它很接近,但它似乎无法在哈希中找到提供的键/值对。我不明白为什么它不能使用提供的哈希来查找符号作为键。
我究竟做错了什么?
由于instance_variable
变量类型不匹配,它不是重复的并且之前已经回答过。如果你看过帖子就说It's close, but it can't seem to find the provided key/value pair in the hash. I don't see why it can't use the provided hash to look up symbols as keys.
。
我这样做的一种方法是翻转任务,例如
def initialize(**h)
h.each do |k, v|
setter = "#{k}="
next unless respond_to? setter # skip if we don't have a setter for this key
public_send setter, v
end
end
这会处理传入的哈希,并为哈希中找到的每个哈希调用赋值操作。它将跳过没有显式setter的任何值。