From: dblack@... Date: 2006-12-08T07:45:22+09:00 Subject: Re: Array changing after concat function Hi -- On Fri, 8 Dec 2006, Drew Olson wrote: > WKC CCC wrote: >> I've found that using: >> >> copy = one.map { |el| el.clone } >> >> will copy all elements into the new array without referring to the same >> object. >> Is there a reason why the clone function has been ommitted from the API >> doc? > > It seems much simpler to just clone the array rather than each element > individually: > > irb(main):001:0> a=[] > => [] > irb(main):002:0> 10.times{|i| a << i} > => 10 > irb(main):003:0> a > => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > irb(main):004:0> b = a.clone > => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > irb(main):005:0> a[0] = 10 > => 10 > irb(main):006:0> a > => [10, 1, 2, 3, 4, 5, 6, 7, 8, 9] > irb(main):007:0> b > => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] But that won't do a deep cloning, which is what it sounds like WKC wants: irb(main):001:0> a = [""] => [""] irb(main):002:0> a[0].object_id => -604580558 irb(main):003:0> a.clone[0].object_id => -604580558 irb(main):004:0> a.map {|e| e.clone }[0].object_id => -604623258 David -- David A. Black | dblack@wobblini.net Author of "Ruby for Rails" [1] | Ruby/Rails training & consultancy [3] DABlog (DAB's Weblog) [2] | Co-director, Ruby Central, Inc. [4] [1] http://www.manning.com/black | [3] http://www.rubypowerandlight.com [2] http://dablog.rubypal.com | [4] http://www.rubycentral.org