0

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

  • 1
    Your example will run but doesn't make a lot of sense in the Ruby context. The parameters to the block (your `v1` through `v4`) receive values from outside of the block, similar to calling a method. There wouldn't be any point to setting those variable names to something completely unrelated inside the block. For the [`times`](https://ruby-doc.org/core-2.4.0/Integer.html#method-i-times) method in particular, `v1` will start off as `0` for the first time through the code and `1` for the second time; the rest will be `nil` both times. – Max Oct 15 '17 at 14:53

1 Answers1

1

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

garythegoat
  • 1,517
  • 1
  • 12
  • 25