如何将可变数量的args传递给yield。 我不想传递一个数组(如下面的代码那样),我实际上想将它们作为程序化数量的args传递给该块。
def each_with_attributes(attributes, &block)
results[:matches].each_with_index do |match, index|
yield self[index], attributes.collect { |attribute| (match[:attributes][attribute] || match[:attributes]["@#{attribute}"]) }
end
end
答案 0 :(得分:14)
使用splat-operator *
将数组转换为参数。
block.call(*array)
或
yield *array
答案 1 :(得分:3)
使用星号将数组展开到参数列表中的各个组件中:
def print_num_args(*a)
puts a.size
end
array = [1, 2, 3]
print_num_args(array);
print_num_args(*array);
将打印:
1
3
在第一种情况下传递数组,在第二种情况下,每个元素分别传递。请注意,被调用的函数需要处理变量参数,例如print_num_args,如果它需要一个固定大小的参数列表并且接收的结果多于或少于预期,那么你将获得异常。
答案 2 :(得分:2)
Asterisk会将数组扩展为ruby中的各个参数:
def test(a, b)
puts "#{a} + #{b} = #{a + b}"
end
args = [1, 2]
test *args