From: Gennady Date: 2003-03-29T07:23:21+09:00 Subject: Re: Need #collect! on partial array ----- Original Message ----- From: "Mike Stok" Newsgroups: comp.lang.ruby To: "ruby-talk ML" Sent: Friday, March 28, 2003 2:01 PM Subject: Re: Need #collect! on partial array > In article <20030328164026.A42337@freeze.org>, > Jim Freeze wrote: > >Hi: > > > >Recently I needed to modify an array. > >The array was part of a hash element, so > >it had to be modified in place. > > > >#collect! would have been a great way to go, > >but I did not need to modify the whole array. > > > >For example > > > > a=%w{one two three} > > > > a.collect! { |i| i.upcase } > > > >will modify the whole array. > > > > a[1..-1].collect! { |i| i.upcase } > > > >will modify the anonymous array created by a[1..-1], > >but not a. > > > >This could have been solved with #collect_with_index! > >but AFAIK, this does not exist. > > > >Is there another way to achieve this same affect? > > [mike@won mike]$ irb > irb(main):001:0> a = %w{one two three} > ["one", "two", "three"] > irb(main):002:0> a[1 .. -1].collect! { |i| i.upcase! } It is cheating, in a way ;-). `i' holds a reference to the original element and your 'upcase!' modifies it in place. You can replace 'collect!' with 'each' and the result will be the same, in other words 'collect!' does not work here at all (to be precise, it modifies an array that will be marked for GC immediately). As far as I understand it is not what the original post meant. > ["TWO", "THREE"] > irb(main):003:0> a > ["one", "TWO", "THREE"] > irb(main):004:0> > > Mike > -- > mike@stok.co.uk | The "`Stok' disclaimers" apply. > http://www.stok.co.uk/~mike/ | GPG PGP Key 1024D/059913DA > mike@exegenix.com | Fingerprint 0570 71CD 6790 7C28 3D60 > http://www.exegenix.com/ | 75D2 9EC4 C1C0 0599 13DA > >