Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a splat parameter from one method to another method

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!

like image 855
user3259492 Avatar asked Nov 25 '25 14:11

user3259492


1 Answers

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
like image 128
falsetru Avatar answered Nov 28 '25 04:11

falsetru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!