Jeremy Smith
Jeremy Smith

Reputation: 15069

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

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.

Upvotes: 15

Views: 2293

Answers (2)

Victor Moroz
Victor Moroz

Reputation: 9225

Did you mean this?

sum(*[1,2,3])

@Dogbert was first

Upvotes: 4

Dogbert
Dogbert

Reputation: 222188

Just put a splat when calling the method?

sum(*[1,2,3])

Upvotes: 24

Related Questions