From: benjohn@... Date: 2007-07-13T21:57:31+09:00 Subject: Re: 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. 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