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

2

15

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.

Bigeye answered 12/7, 2011 at 20:41 Comment(0)
M
24

Just put a splat when calling the method?

sum(*[1,2,3])
Monophagous answered 12/7, 2011 at 20:44 Comment(0)
H
4

Did you mean this?

sum(*[1,2,3])

@Dogbert was first

Homolographic answered 12/7, 2011 at 20:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.