Sum the value of array in hash
You can use inject
to sum all the amounts. You can then just put the result back into a hash if you need to.
arr = [{:amount=>10, :gl_acct_id=>1, :alt_amount=>20}, {:amount=>20, :gl_acct_id=>2, :alt_amount=>30}]
amount = arr.inject(0) {|sum, hash| sum + hash[:amount]} #=> 30
{:amount => amount} #=> {:amount => 30}
Rails sum values in an array of hashes
You could use each_with_object
with a Hash and a default value:
array = [
{loading: 10, avg: 15, total: 25 },
{loading: 20, avg: 20, total: 40 },
{loading: 30, avg: 25, total: 55 }
]
sum = Hash.new(0)
array.each_with_object(sum) do |hash, sum|
hash.each { |key, value| sum[key] += value }
end
# => {:loading=>60, :avg=>60, :total=>120}
It will work with any number of keys, and won't complain if a key isn't present in all the hashes.
BTW, you can replace
array.map { |h| h[:loading] }.sum
with
array.sum { |h| h[:loading] }
Sum values in array of hash if they have the same value
This seems work
array.group_by { |item| [item[:loading], item[:avg]] }.values.flat_map { |items| items.first.merge(total: items.sum { |h| h[:total] }) }
=> [{:loading=>10, :avg=>15, :total=>25}, {:loading=>20, :avg=>20, :total=>120}, {:loading=>30, :avg=>25, :total=>55}, {:loading=>10, :avg=>20, :total=>46}]
How to calculate the sum of array inside hash ruby
You should use:
total_hours = @payload[:activities].sum{|activity| activity[:hours].to_f}
You see, what you're wanting to do is, essentially:
[
{
:project=>1,
:activity=>"my activity",
:hours=>0.2e1,
:date=>Sat, 10 Aug 2019 00:00:00 UTC +00:00
},
{
:project=>2,
:activity=>"Tester",
:hours=>0.2e1,
:date=>Thu, 01 Aug 2019 00:00:00 UTC +00:00
},
{
:project=>2,
:activity=>"Tester",
:hours=>0.3e1,
:date=>Thu, 01 Aug 2019 00:00:00 UTC +00:00
}
].sum{|activity| activity[:hours].to_f}
But, you're calling .sum
on the @payload
variable, which is a hash. What you want is the value of the hash that is associated with the key :activities
. Thus, you need to call .sum
on @payload[:activities]
where @payload[:activities]
returns the array above.
Get hash values (from a number of hashes) in an array and sum them up
To sum the values of a hash:
{a:1,b:2}.values.sum
#=> 3
And to do that for your array of hashes:
total_order.flat_map(&:values).sum
#=> 15.0
Note that sum
is only available in Ruby 2.4.0 and later (and in Rails). In older versions you can use reduce(:+)
and inject(:+)
instead of sum
.
Better way to sum values in an array of hashes
I like using the map/reduce metaphor like so:
total_sales = sales.map {|s| s['sale_price']}.reduce(0, :+)
The reduce method is a synonym for the inject method, I find the name inject to be somewhat confusing with the memo component. It has another form I use above to take the initial value and a reference to a method call used for the combination/reduction process.
I think the overall pattern of mapping the values and then reducing them to an aggregate is well known and self-documenting.
EDIT: Use symbol :+ instead of proc reference &:+
How to sum the value of hashes in array with condition
One way using sum
:
records.sum { |h| h["status"] ? h["number"] : 0 } #=> 10000
Get sum of key values in deep array of hashes
Regarding ruby-on-rails
tag, you can use Ruby method #inject
with Rails method #deep_merge
:
array.inject do |hash1, hash2|
hash1.deep_merge(hash2) do |key, hash1_val, hash2_val|
hash1_val + hash2_val
end
end
=> {:john=>{:win=>30, :lose=>60}, :mike=>{:win=>15, :lose=>15}}
Related Topics
How to Decompress Gzip String in Ruby
Rails - Sort by Join Table Data
Asynchronous Http Request in Ruby
Ruby on Rails Rmagick on Windows 7
Convert Time to Other Timezone
Rvm Is Not a Function, Selecting Rubies with 'Rvm Use ...' Will Not Work
Rails: Should Partials Be Aware of Instance Variables
Get Current Ruby Process Memory Usage
What Are the Differences Between "Private", "Public", and "Protected Methods"
How to Make Instance Variables Private in Ruby
Put a Link in a Flash[:Notice]
Dynamically Set Local Variables in Ruby
How to Iterate Activerecord Attributes, Including Attr_Accessor Methods
Rails, Postgresql, and History Triggers
Ruby/Rails: Converting a Date to a Unix Timestamp
Ruby on Rails Plural (Controller) and Singular (Model) Convention - Explanation