Loop over an array that changes the elements

Hi,

I have a rather simple question. I have an array and want to change the
elements of the array in a loop. For example in Java, you would write:

int[] numbers = {1, 2, 3}

for(int i = 0; i < numbers.length; i++)
{
numbers[i] = numbers[i] * 2
}

In Ruby the common way to loop over an array is Array#each

But

numbers = [1, 2, 3]

numbers.each do |num|
num = num * 2
end

would not change the array itself.

Of course, you can write something like

for i in 0 … numbers.length-1 do
numbers[i] = numbers * 2
end

But this in my eyes is not really the Ruby way. Is there a standard way
of doing this?

Thx a lot!

On 7/13/07, Bernd B. [email protected] wrote:

}

numbers.map!{ |x| x*2 }
HTH
Robert

would not change the array itself.
No it would point num to a new Integer simply, you can only change the
objects num refers to, but in our case as these objects are immutable
Integers it wont work.
Consider Strings which are muteable in ruby, and try this code ( best in
irb )
letters=%w{a b c}
letters.each do | letter |
letter << “*”
end

Still I prefer
letters.map{ |l| l << “" }
although
letters.map!{ |l| l + "
” }
is probably much cleaner code :slight_smile:

HTH
Robert

Of course, you can write something like

for i in 0 … numbers.length-1 do
numbers[i] = numbers * 2
end

But this in my eyes is not really the Ruby way. Is there a standard way
of doing this?
Well spotted Bernd :wink:

Thx a lot!


Posted via http://www.ruby-forum.com/.

HTH
Robert

}
end
of doing this?
numbers = numbers.map {|number| numer * 2}

Cheers,
B

El Jul 13, 2007, a las 2:53 PM, [email protected]
escribió:

numbers = numbers.map {|number| numer * 2}

Even, to be closer to the in-place editing,

numbers.map! {|n| n*2}

– fxn

}
end

would not change the array itself.

You’re right.

As others and I have said, the map solution is good here.

numbers = numbers.map {|number| number*2}

If you really wanted to change the array itself though, you could do
this:

numbers.each_index {|i| numbers[i] = numbers[i] * 2}

or

numbers.each_index {|i| numbers[i] *= 2}

Thanks,
Benj

On 7/13/07, [email protected] [email protected] wrote:

}
end
of doing this?

numbers = numbers.map {|number| numer * 2}
Hmm what about the GC?

On 7/13/07, Daniel M. [email protected] wrote:

Actually, as I think someone already posted, map! is probably the most
idiomatic way of doing this:

Daniel this is great I am not in your killfile :slight_smile:

Robert

[email protected] writes:

As others and I have said, the map solution is good here.

numbers = numbers.map {|number| number*2}

If you really wanted to change the array itself though, you could do this:

numbers.each_index {|i| numbers[i] = numbers[i] * 2}

Actually, as I think someone already posted, map! is probably the most
idiomatic way of doing this:

numbers.map! {|x| 2*x}