ruby-on-railsrubyruby-block

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)?


Solution

  • 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