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.

Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
Jeremy Smith
  • 14,727
  • 19
  • 67
  • 114

2 Answers2

24

Just put a splat when calling the method?

sum(*[1,2,3])
Dogbert
  • 212,659
  • 41
  • 396
  • 397
4

Did you mean this?

sum(*[1,2,3])

@Dogbert was first

Victor Moroz
  • 9,167
  • 1
  • 19
  • 23