On Tue, Sep 18, 2012 at 9:36 AM, Damjan Rems <[email protected]> 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/
-- You received this message because you are subscribed to the Google Groups
ruby-talk-google group. To post to this group, send email to
[email protected]. To unsubscribe from this group, send email
to [email protected]. For more options, visit this
group at https://groups.google.com/d/forum/ruby-talk-google?hl=en