Hi --

On Thu, 12 Jun 2008, Rick DeNatale wrote:

> On Wed, Jun 11, 2008 at 5:50 PM, Tim Hunter <TimHunter / nc.rr.com> wrote:
>
>> Jason Lillywhite wrote:
>>
>>> So let me ask you this:
>>>
>>> going back to
>>>
>>> sum = [1,3,5].inject(0) {|s,e| s+e}
>>> puts sum
>>>
>>> what if you want to return an array that shows each step of the way, such
>>> that:
>>>
>>> sum => [1,4,9]
>>>
>>> ??
>>>
>> irb(main):003:0> steps = []
>> => []
>> irb(main):004:0> sum = [1,3,5].inject(0) {|s,e| steps << s+e; steps.last}
>> => 9
>> irb(main):005:0> p steps
>> [1, 4, 9]
>
>
> Here's a way to do it without the extra variable:
>
> [1,3,5].inject([]) {|s,e| s = s.to_a; s << e + ( s.last || 0)}
>
> or if you still want to inject 0 as the starting value:
>
> [1,3,5].inject(0) {|s,e| s = s.to_a; s << e + s.last}[1..-1]
>
> Now these will give a deprecation warning since Ruby 1.9 does away with
> Object#to_a, an alternative is:
>
> [1,3,5].inject(0) {|s,e| s = [s].flatten; s << e + s.last}[1..-1]

And yet another way:

   [1,3,5].inject([0,[]]) {|(i,acc),e| [i+e, acc << i+e]}[1]

I suspect each_cons could get involved there somewhere....


David

-- 
Rails training from David A. Black and Ruby Power and Light:
   INTRO TO RAILS         June 9-12            Berlin
   ADVANCING WITH RAILS   June 16-19           Berlin
   ADVANCING WITH RAILS   July 21-24           Edison, NJ
See http://www.rubypal.com for details and updates!