From: Eric Hodel Date: 2011-07-25T09:41:27+09:00 Subject: Re: best style for setting items in a collection On Jul 24, 2011, at 9:25 AM, Marshall Farrier wrote: > 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. Using each_with_index: month_lengths = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] total_lengths = [0] month_lengths.each_with_index do |length, i| total_lengths[i] = length + total_lengths[i - 1] end p total_lengths Here's a version using inject: month_lengths = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] total_lengths = [0] month_lengths.inject do |length, total| total += length total_lengths << total total end p total_lengths