On Thu, Sep 30, 2010 at 3:35 PM, F. Senault <fred / lacave.net> wrote:
> def factorial(n)
> 1..n).inject(1, :*)
> end
> (I don't like much the second one, it's a bit less legible.)

lose the 1.
on my case, i do like the second very much. more idiomatic. less prone
to typo. less to think (convention ie).

i am referring of course, not to the factorial, but of the idiom,

   enum.inject :operator
   enum.inject factor, :operator

eg,

multiplying

>> (1..5).inject :*
=> 120
>> (2..5).inject :*
=> 120
>> (3..5).inject :*
=> 60

adding

>> (4..5).inject( :+ )
=> 9

multiply w factor

>> (3..5).inject 5, :*
=> 300

adding w initial,

>> (4..5).inject( 100, :+ )
=> 109

powers,

>> (2..3).inject :**
=> 8

>> (2..4).inject :**
=> 4096

and  more fun using blocks..

best regards -botp