Another valid option would be

def sum(*numbers)
  numbers.reduce(&:+)
end

On Thu, Nov 20, 2014 at 3:32 PM, Robert Klemme <shortcutter / googlemail.com>
wrote:

> On Thu, Nov 20, 2014 at 4:09 PM, Roelof Wobben <r.wobben / home.nl> wrote:
>
> > I had to do numbers.inject
>
> Exactly.
>
> > One other problem.
> > The method schould reject everything which is not a integer.
> > numbers.inject gives a error if you do sum (1,"a", 2)
>
> Well, then it _does_ reject non numbers. Generally I probably would
> not add a test to that method that simply skips non numbers.  Let each
> method do one thing properly.  If you need filtering you can always do
> the filtering before the call.
>
> sum(*numbers.grep(Integer))
>
> Btw, I would declare the interface of the method like this:
>
> def sum(numbers)
>
> i.e. use a single Enumerable.  I think that is more flexible because
> you can pass in an Enumerator which can be used to delegate the
> filtering to the iteration (and not have to do it upfront and convert
> to an Array like is needed with *numbers):
>
> irb(main):004:0> def sum(n) n.inject(0){|s,x|s+x} end
> => nil
> irb(main):005:0> sum([1,2,"foo"].to_enum(:grep, Integer))
> => 3
>
> Kind regards
>
> robert
>
>
> --
> [guy, jim].each {|him| remember.him do |as, often| as.you_can - without
> end}
> http://blog.rubybestpractices.com/
>



-- 
George Drummond
Software Engineer

+44 (0)333 240 2222


[image: Rentify]
 6-8 Long Lane, London EC1A 9HF
 www.rentify.com