otherCount = @products.drop(3).inject(0) { |sum,count| sum, count }
My Ruby environment is 1.9.3.
products
is an array of hashes elements. It has properties: productName
and count
. I want to sum up the count values of all the hashes in the products
array (with the exception of the first 3 hashes). Documentation I've found are either too brief in their explanation or use a different Ruby environment, which may likely be the problem. The code I wrote is written as per this document.
I drop the first 3 elements, then call inject
, with an initial value of 0, carry over variable called sum
, and count
is the name of the field in each of the hashes whose value I want to add up.
Change
inject(0) { |sum,count| sum, count }
to
inject(0) { |sum,p| sum + p['count'] }
If you're having trouble integrating this, copy and paste these 2 lines into an irb
session to verify this works:
a = [{'count' => 1},{'count' => 2},{'count' => 3}]
a.inject(0) { |sum,p| sum + p['count'] }
# => 6
Hopefully this helps bridge the gap.