I have an object of a class, and I want to duplicate it with dup
. One of the instance variables is an array, and it seems to be referencing it. I thought dup actually created a DUPLICATE.
Here's my IRB session:
irb(main):094:0> class G
irb(main):095:1> attr_accessor :iv
irb(main):096:1> def initialize
irb(main):097:2> @iv = [1,2,3]
irb(main):098:2> end
irb(main):099:1> end
=> nil
irb(main):100:0> a=G.new
=> #<G:0x27331f8 @iv=[1, 2, 3]>
irb(main):101:0> b=a.dup
=> #<G:0x20e4730 @iv=[1, 2, 3]>
irb(main):103:0> b.iv<<4
=> [1, 2, 3, 4]
irb(main):104:0> a
=> #<G:0x27331f8 @iv=[1, 2, 3, 4]
I would expect a
to be unchanged, because dup
creates a whole new variable, not reference.
Also note that if you were to replace [1,2,3]
with a scalar in G::initialize
, dup
will not reference it.