From: timr Date: 2009-12-29T15:45:06+09:00 Subject: Re: PLEASE HELP...dup is not working correctly in the following code On Dec 28, 10:20 pm, Seebs wrote: > On 2009-12-29, timr wrote: > > > You are right about the strings having the same object_ids in each > > object, which explains why the modification on the dupped object > > affects the original strings. That helps. But the suggested strategy > > doesn't solve the problem: > > Hmm. > > >>> a = [['a', 'b'], ['c','d']] > >=> [["a", "b"], ["c", "d"]] > >>> a.each{|r| r.each{|letter| p letter.object_id}} > > 4442750 > > 4442740 > > 4442710 > > 4442700 > >=> [["a", "b"], ["c", "d"]] > >>> b = a.map{|r| r.each{|letter| letter.dup}} > > This doesn't seem right.  The inner loop (which is the one I think > we care about) is using each, not map.  So we never actually return > the array consisting of all the duplicated letters. > > If you have an array of arrays, I think you need to use map at both > levels. > > irb(main):001:0> a = [['a', 'b'], ['c','d']] > => [["a", "b"], ["c", "d"]] > irb(main):002:0> b = a.map {|r| r.map{|l| l.dup}} > => [["a", "b"], ["c", "d"]] > irb(main):003:0> a.each{|r| r.each{|letter| p letter.object_id}} > 2152912244 > 2152912216 > 2152912132 > 2152912104 > => [["a", "b"], ["c", "d"]] > irb(main):004:0> b.each{|r| r.each{|letter| p letter.object_id}} > 2152886456 > 2152886316 > 2152886232 > 2152886176 > => [["a", "b"], ["c", "d"]] > > What's throwing you off here is that .each returns the array object > it started with. > > So "r.each {...}" always returns r, unmodified. > > -s > -- > Copyright 2009, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.nethttp://www.seebs.net/log/<-- lawsuits, religion, and funny pictureshttp://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated! I was just going to post that correction after I realized that mistake. Thanks for the help.