From: Josh Cheek Date: 2011-07-24T23:16:53+09:00 Subject: Re: best style for setting items in a collection --bcaec51b97a7a0e2fa04a8d15959 Content-Type: text/plain; charset=ISO-8859-1 On Sat, Jul 23, 2011 at 8: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. > > -- > Posted via http://www.ruby-forum.com/. > > It's hard to know how to answer this because you're overwriting the values of indexes that you use in calculations later on. This seems like it is probably unintentional: If arr was [1,1,1], then are you expecting [1,2,2] -- the value at index 2 is calculated based on the original value at index 1. Or are you expecting [1,2,3] -- the value at index 2 is calculated based on the new value at index 1? If the former, then this is equivalent: arr.each_cons(2).with_index(1) do |(left, right), index| arr[index] = left + right end If the latter, then this is equivalent: (1...arr.length).each { |index| arr[index] += arr[index-1] } --bcaec51b97a7a0e2fa04a8d15959--