I'm currently following the tutorials over at RubyMonk, and one of the problems I need to solve is to write a subtract
function that would meet these conditions:
- invoking
subtract(4, 5)
should return-1
- invoking
subtract(-10, 2, 3)
should return-15
- invoking
subtract(0, 0, 0, 0, -10)
should return10
Coming from a traditional imperative programming background (C, Lua, Java, etc.), my first attempt would have been something like this:
def subtract *numbers
start = numbers[0]
tail = numbers.drop(1)
for i in tail do
start -= i
end
return start
end
But, this just felt wrong in Ruby, and I don't doubt that it is. Trying to use a more Ruby-esque style, I thought it would be better to use some of Array
's methods.
Here is my latest version:
def subtract *numbers
(numbers.drop 1).inject(numbers[0]) { |x, y| x-y}
end
One thing to note is that this is essentially the same thing as above, I just moved most of the looping into Array#inject
. To me, simply moving logic isn't a new style per se, and so conceptually this is nothing new to me.
Therefore my questions are:
- Is this true Ruby style? If not, how could I make it so, and how would that new style differ from the current?
- Is there any way to improve readability? ('Cause honestly the current version lacks quite a bit).