Subtract values of a array

Hello,

I changed from ruby koans to rubymonks.

Now I have to make a method which can substract any number of numbers.

So I tried this

def subtract(*numbers)
numbers.inject(0) { |sum, number| sum - number }
end

but that won’t work subtract ( 4,5) gives -9 when -1 is the right
answer.

Can anyone give me a tip for a better answer.

Roelof

On Friday 28 September 2012 Roelof W. wrote

end

but that won’t work subtract ( 4,5) gives -9 when -1 is the right answer.

Can anyone give me a tip for a better answer.

Roelof

Do you mean you want a method which subtracts some numbers from a given
one
(for example: subtract(10,3,4) should give 10 - 3 - 4)? In this case,
I’d say
you need a required parameter, which is the number to subtract from and
which
you pass as first argument to inject.

To see why your method doesn’t do what you want, check the documentation
for
inject and, in particular, what the parameter means.

I hope this helps

Stefano

On Thu, Sep 27, 2012 at 5:36 PM, Roelof W. [email protected]
wrote:

end

but that won’t work subtract ( 4,5) gives -9 when -1 is the right answer.

Can anyone give me a tip for a better answer.

inject(0) will pass 0 as the first accumulator. If you don’t pass the
0, then inject will use the first element in the array as the first
accumulator, which is what you want I think.

Jesus.

Thanks for all the help.
And overthinking is a well known problem for me.

Roelof

On Thu, Sep 27, 2012 at 11:36 AM, Roelof W. [email protected]
wrote:

def subtract(*numbers)
numbers.inject(0) { |sum, number| sum - number }
end

but that won’t work subtract ( 4,5) gives -9 when -1 is the right answer.

You’re overthinking it. Look at a simpler usage of inject.

I find it useful to think of inject as injecting the operation between
each element of the array it’s given, and if it’s given an argument as
well (not an operation, one to treat as a starting value), then
between that and the start as well. So what you’ve done there is tell
it to do, essentially, 0 - 4 - 5. All you want is 4 - 5. How would
you eliminate the “0 -” part? Hint: the argument is optional.

-Dave

On Thu, Sep 27, 2012 at 11:53 AM, Roelof W. [email protected]
wrote:

Thanks for all the help.
And overthinking is a well known problem for me.

You’re welcome. One big thing to get used to in Ruby is that it tries
to make things easy for you. C tries to make things easy for the
compiler writers. Java tries to make it easy for the machine. Ruby
is a refreshing change. This becomes even more important if you start
doing Rails – go with what it provides for you, and it will be easy,
but try to deviate from its conventions, and you will have a much
harder time.

-Dave

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs