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.
请注意,我无法更改sum方法以接受数组。
2 个解决方案
#1
23
Just put a splat when calling the method?
调用方法时只需要一个splat?
sum(*[1,2,3])
#2
4
Did you mean this?
你的意思是这个吗?
sum(*[1,2,3])
@Dogbert was first
@Dogbert是第一个
#1
23
Just put a splat when calling the method?
调用方法时只需要一个splat?
sum(*[1,2,3])
#2
4
Did you mean this?
你的意思是这个吗?
sum(*[1,2,3])
@Dogbert was first
@Dogbert是第一个