From: Marshall Farrier Date: 2011-07-25T01:25:04+09:00 Subject: Re: best style for setting items in a collection Josh Cheek wrote in post #1012707: > On Sat, Jul 23, 2011 at 8:41 PM, Marshall Farrier > wrote: > >> arr[i] += arr[i - 1] >> 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] } Ok, sorry that my example muddled things so much. I did mean the latter. The point of departure is that arr initially holds the (non-leap-year) number of days in each month with 0 up front for month 0: [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]. Then I want to modify it so that it holds the aggregate days in normal years up to the end of the month in question. I then use this array for various date calculations. -- Posted via http://www.ruby-forum.com/.