From: Eric Hodel Date: 2011-07-24T16:57:58+09:00 Subject: Re: best style for setting items in a collection On Jul 23, 2011, at 6:41 PM, Marshall Farrier wrote: > I've only recently started learning Ruby and notice in Thomas' > Programming Ruby 1.9 that it seems to be stylistically preferable (and > presumably also faster fwiw) not to use a for loop but rather to use the > each method as often as possible. But I'm having trouble using combining > that with re-assigning values inside an array. > > More specifically, consider the following problem: We have an array of > integers and want the result to be the same as the following for loop: > > for i in 1...arr.length > arr[i] += arr[i - 1] > end > > Is it stylistically better to use the for loop here or do something like > this: > > 1.upto(arr.length - 1) {|i| arr[i] += arr[i - 1]} > > Or is there another way of doing it that is better than both of these? I > feel like I should be able to do this using the each method but can't > figure out how to make the assignment work that way, and the upto > version is pretty short and sweet. I'm not sure what you're calculating here, but if I wanted to add the items in an Array with one item to the left I would use: arr.zip(arr.rotate).map { |a, b| a + b } This doesn't calculate the same result as yours, but I'm not sure exactly what you want to do.