From: Robert Klemme Date: 2012-09-18T16:49:55+09:00 Subject: Re: Bug or feature On Tue, Sep 18, 2012 at 9:36 AM, Damjan Rems wrote: > There has probably been some discussion about this problem so sorry if I > am repeating but it is so crucial that should be mention every once in a > while. > > This simple example: > > a=['0'] > 1.upto(2) do > b = a.clone > c = a.clone > b[0] << '1' > c[0] += '2' > end > p a > > yields ['011'] in ruby 1.8.6 and 1.9.3. I think that it should be ['0'] > > I understand the difference between << an += operator but shouldn't > clone method make a duplicate of object a, without any link to original > object. > > Or am I missing something. Yes. #clone is just shallow copy. irb(main):002:0> a=['foo', 'bar'] => ["foo", "bar"] irb(main):003:0> a.map &:object_id => [-1072256208, -1072256218] irb(main):004:0> b = a.clone => ["foo", "bar"] irb(main):005:0> b.map &:object_id => [-1072256208, -1072256218] irb(main):006:0> a.zip(b).all? {|x,y| x.equal? y} => true For full object tree copy you can do irb(main):007:0> c = Marshal.load(Marshal.dump(a)) => ["foo", "bar"] irb(main):008:0> c.map &:object_id => [-1072289088, -1072289108] irb(main):009:0> a.zip(c).all? {|x,y| x.equal? y} => false Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/