I would like to create methods called 'add' and 'subtract' using splat parameter as below:
def add(*numbers)
numbers.inject(0) { |sum, n| sum + n }
end
def subtract(*numbers)
numbers[0] - add(numbers[1..-1])
end
But it didn't work. What should I do to pass the splat parameter from one to another? (Especially for some specific range...)
Thank you!
When you call add function, add * before the array object to unpack array as multiple arguments.
def add(*numbers)
numbers.inject(0) { |sum, n| sum + n }
end
def subtract(*numbers)
numbers[0] - add(*numbers[1..-1])
# ^
end
subtract(9, 0, 1, 2) # => 6
subtract(9, 1) # => 8
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With