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>
Citizens for MWI [map_with_index] welcomes you to its ranks But I
think it’s been rejected.
Well, it’s nice to finally find a group that welcomes me.
It’s just my luck that the group has been disbanded even
before I was invited to be a member.
Is there another way to achieve this same affect?
You could do some variant of:
(0…a.size).each {|i| <do something, or not, with a[i]>}
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.
Right… for example, if instead of uppercasing
some strings you were incrementing some
integers, this wouldn’t work.
Hal
···
----- Original Message -----
From: “Gennady” gfb@tonesoft.com
To: “ruby-talk ML” ruby-talk@ruby-lang.org
Sent: Friday, March 28, 2003 4:23 PM
Subject: Re: Need #collect! on partial array