Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass an array to a method that accepts an attribute with a splat operator?

Tags:

ruby

splat

If I have a method like:

def sum *numbers
  numbers.inject{|sum, number| sum += number}
end

How would I be able to pass an array as numbers?

ruby-1.9.2-p180 :044 > sum 1,2,3   #=> 6
ruby-1.9.2-p180 :045 > sum([1,2,3])   #=> [1, 2, 3]

Note that I can't change the sum method to accept an array.

like image 504
Jeremy Smith Avatar asked Jan 24 '26 17:01

Jeremy Smith


2 Answers

Just put a splat when calling the method?

sum(*[1,2,3])
like image 133
Dogbert Avatar answered Jan 27 '26 01:01

Dogbert


Did you mean this?

sum(*[1,2,3])

@Dogbert was first

like image 25
Victor Moroz Avatar answered Jan 27 '26 01:01

Victor Moroz



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!