From: Rick DeNatale Date: 2008-06-12T07:49:18+09:00 Subject: Re: Array inject function problem ------=_Part_9199_14912552.1213224579591 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Content-Disposition: inline On Wed, Jun 11, 2008 at 5:50 PM, Tim Hunter 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] -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/ ------=_Part_9199_14912552.1213224579591--