From: Serabe Date: 2008-07-15T05:24:52+09:00 Subject: Re: Factorials 2008/7/14 Victor Reyes : > The "Rubish" version of your factorial solutions appear to be much faster! > Although I find it more confusing than the "traditional" recursive solution. > I guess my problem is understanding the role of the *inject* method. > I use 100 instead of 5 to make it run a bit longer. Copied from ri documentation for Enumerable#inject: ------------------------------------------------------ Enumerable#inject enum.inject(initial) {| memo, obj | block } => obj enum.inject {| memo, obj | block } => obj ------------------------------------------------------------------------ Combines the elements of _enum_ by applying the block to an accumulator value (_memo_) and each element in turn. At each step, _memo_ is set to the value returned by the block. The first form lets you supply an initial value for _memo_. The second form uses the first element of the collection as a the initial value (and skips that element while iterating). # Sum some numbers (5..10).inject {|sum, n| sum + n } #=> 45 # Multiply some numbers (5..10).inject(1) {|product, n| product * n } #=> 151200 # find the longest word longest = %w{ cat sheep bear }.inject do |memo,word| memo.length > word.length ? memo : word end longest #=> "sheep" # find the length of the longest word longest = %w{ cat sheep bear }.inject(0) do |memo,word| memo >= word.length ? memo : word.length end longest #=> 5 Regards, Serabe -- http://www.serabe.com