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.
Just put a splat when calling the method?
sum(*[1,2,3])
Did you mean this?
sum(*[1,2,3])
@Dogbert was first
精彩评论