From: Robert Dober Date: 2007-07-13T20:52:56+09:00 Subject: Re: Loop over an array that changes the elements On 7/13/07, Bernd Burnt wrote: > 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 > } > numbers.map!{ |x| x*2 } HTH Robert > > 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. 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 :) 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 ;) > > Thx a lot! > > -- > Posted via http://www.ruby-forum.com/. > > HTH Robert -- I always knew that one day Smalltalk would replace Java. I just didn't know it would be called Ruby -- Kent Beck