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