From: Rick DeNatale Date: 2008-07-15T00:16:49+09:00 Subject: Re: Factorials ------=_Part_55429_11728833.1216048882137 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Content-Disposition: inline On Mon, Jul 14, 2008 at 10:52 AM, Dave Bass wrote: > Victor Reyes wrote: > > I guess my problem is understanding the role of the *inject* method. > > Same problem here. But I figured out it's ideal for calculating > summations and products, where you'd use a big Sigma or Pi in > mathematics. :-) > > Surprisingly Fortran never had Sigma or Pi constructs; we had to roll > our own using a DO loop. Same for subsequent languages. Ruby is the > first language I've come across with it built in. > > Maybe someone would explain why it's called "inject" though? > I believe that Matz took the name from Smalltalk, where the equivalent to Ruby's collection.inject(0) {|sum, element| sum + element } would be: collection inject: 0 into: [sum, element | sum + element] The idea is that this method 'injects' the first value into the sequence, which is handy in some cases. This is an 'enhanced' version of what is called reduce in many other functional and functional-influenced languages. Ruby allows the injection argument to be omitted in the call, which makes the name a bit more mysterious. Without the injection argument Ruby's inject works just like reduce, and Ruby 1.9 makes reduce an alias for inject. -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/ ------=_Part_55429_11728833.1216048882137--