[英]Ruby - Apply method on all block variables
Having for example sum = 0 例如,sum = 0
2.times do |v1, v2, v3 , v4|
v1 = FactoryGirl...
v2 = FactoryGirl...
..
v4 = ...
sum =
end
Now on sum I would like to add the value of an attribute that each object from the block has it eg 现在总的来说,我想添加一个属性值,该属性来自块中的每个对象,例如
sum = v1[:nr_sales] + v2[:nr_sales] +...
Is there a way to do this at once (apply method for all args of the block)? 有没有办法立即执行此操作(将方法应用于该块的所有参数)?
Splat operators are accepted in block parameters: 程序段参数接受Splat运算符:
def foo
yield 1, 2, 3, 4
end
foo { |*args| puts args.inject(:+) } #=> 10
So in your case you could do something like: 因此,在您的情况下,您可以执行以下操作:
2.times do |*args|
sum = args.sum { |h| h[:nr_sales] }
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.