class Foo
def bar
@instance_variable = [['first']]
# make a duplicate object with the :dup method
local_variable=@instance_variable.dup
# They have different object_id
p @instance_variable.object_id
p local_variable.object_id
local_variable.each{|n|n.push('second')}
@instance_variable
end
end
f=Foo.new
p f.bar
=> 2000
=> 2002
=> [["first", "second"]]
似乎 local_variable 仍然引用@instance_variable,尽管它是一个不同的对象。这种行为在每个块中都有push
。unshift
使用像这样的正常分配local_variable='second'
,结果符合预期=> [['first']]
不明白为什么local_variable.each{|n|n.push('second')}
会影响@instance_variable
使用 Ruby-1.9.2p318