开发者

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

开发者 https://www.devze.com 2023-03-20 01:20 出处:网络
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?

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

0

精彩评论

暂无评论...
验证码 换一张
取 消