Ruby - 对所有块变量应用方法
Ruby - Apply method on all block variables
例如有
总和 = 0
2.times do |v1, v2, v3 , v4|
v1 = FactoryGirl...
v2 = FactoryGirl...
..
v4 = ...
sum =
end
总而言之,我想添加块中每个对象都具有的属性值,例如
sum = v1[:nr_sales] + v2[:nr_sales] +...
有没有办法一次性做到这一点(对块的所有参数应用方法)?
块参数中接受 Splat 运算符:
def foo
yield 1, 2, 3, 4
end
foo { |*args| puts args.inject(:+) } #=> 10
所以在你的情况下,你可以这样做:
2.times do |*args|
sum = args.sum { |h| h[:nr_sales] }
end
例如有 总和 = 0
2.times do |v1, v2, v3 , v4|
v1 = FactoryGirl...
v2 = FactoryGirl...
..
v4 = ...
sum =
end
总而言之,我想添加块中每个对象都具有的属性值,例如
sum = v1[:nr_sales] + v2[:nr_sales] +...
有没有办法一次性做到这一点(对块的所有参数应用方法)?
块参数中接受 Splat 运算符:
def foo
yield 1, 2, 3, 4
end
foo { |*args| puts args.inject(:+) } #=> 10
所以在你的情况下,你可以这样做:
2.times do |*args|
sum = args.sum { |h| h[:nr_sales] }
end