简体   繁体   中英

Ruby - Apply method on all block variables

Having for example 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM