From: John Feminella Date: 2011-05-04T09:44:27+09:00 Subject: Re: Iterating over an Array of Hashes On Tue, May 3, 2011 at 20:34, 7stud -- wrote: > Peter Hicks wrote in post #996483: >> >> What is the magic I am missing? >> > > clone(): `clone` doesn't cut it, since it's creating shallow copies. An illustration of the problem: ==== begin snippet ==== arr = [{:fruit => {:kind => 'apple'}}, {:fruit => {:kind => 'banana'}}] # => [{:fruit=>{:kind=>"apple"}}, {:fruit=>{:kind=>"banana"}}] arr.map(&:clone).each { |h| h[:fruit][:kind] = 'coconut' } # => [{:fruit=>{:kind=>"coconut"}}, {:fruit=>{:kind=>"coconut"}}] ==== end snippet ==== Notice that `arr` now has coconuts in it, instead of the original apples and bananas. ~ jf -- John Feminella Principal Consultant, BitsBuilder LI: http://www.linkedin.com/in/johnxf SO: http://stackoverflow.com/users/75170/ On Tue, May 3, 2011 at 20:34, 7stud -- wrote: > Peter Hicks wrote in post #996483: >> >> What is the magic I am missing? >> > > clone(): > > b = [ { :x => "foo" }, { :x => "bar" }, { :x => "baz" } ] > count = 0 > > b.each do |x| >  copy = x.clone >  copy[:x] = count >  count += 1 > >  puts copy[:x] > end > > b.each do |x| >  p x > end > > --output:-- > 0 > 1 > 2 > {:x=>"foo"} > {:x=>"bar"} > {:x=>"baz"} > > -- > Posted via http://www.ruby-forum.com/. > >