Hi --

On Thu, 13 Mar 2008, Artem Voroztsov wrote:

> # One could write
> module Enumerable
>  def sum
>    inject(0) {|f,x| f+x}
>  end
> end
>
> # And we have
> puts [1,2,3,4].sum # => 10
>
> # But it works only for numbers.
> # I would like to write more general code:
>
> module Enumerable
>  def sum
>    each.skip_first.inject(first) {|f,x| f+x}
>  end
> end
>
> # so we have:
> puts [1,2,3,4].sum #=> 10
> puts ['a','b','c'].sum #=> 'abc'
> ------------------------
>
> 1) Is it a good idea to add method ''first' to  Enumerable?
> 2) Please, show me the _right_ code for Enumerator#skip_first(n=1) (ruby1.9)

If you don't give an argument to inject, it uses the first element in
the collection. So you can just do:

   %w{a b c}.inject {|acc,e| acc + e }


David

-- 
Upcoming Rails training from David A. Black and Ruby Power and Light:
   ADVANCING WITH RAILS, April 14-17 2008, New York City
   CORE RAILS, June 24-27 2008, London (Skills Matter)
See http://www.rubypal.com for details. Berlin dates coming soon!