B
Bernd Burnt
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 = numbers * 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 = 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!
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 = numbers * 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 = 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!