tags:

views:

248

answers:

2

I'm just learning Ruby so apologies if this is too newbie for around here, but I can't work this out from the pickaxe book (probably just not reading carefully enough). Anyway, if I have an array like so

arr = [1,2,3,4,5]

and I want to, say, multiply each value in the array by 3, I have worked out that doing the following

arr.each {|item| item *= 3}

will not get me what I want (and I understand why, I'm not modifying the array itself).

What I don't get is how to modify the original array from inside the code block after the iterator. I'm sure this is very easy.

+6  A: 

You should probably use map instead of directly modifying the array:

arr = arr.map {|item| item * 3}

If you really want to modify the array directly, do this:

arr.each_with_index {|item, index| arr[index] = item * 3}

Mark Byers
If you really need to modify each element, using map would definitely be more elegant, imho.
x3ro
And if you want to modify the array itself use map! instead
Yoann Le Touche
+2  A: 

To directly modify the array, use arr.map! {|item| item*3}. To create a new array based on the original (which is often preferable), use arr.map {|item| item*3}. In fact, I always think twice before using each, because usually there's a higher-order function like map, select or inject that does what I want.

Chuck