Skip to content

Instantly share code, notes, and snippets.

@andynu
Created December 14, 2011 17:08
Show Gist options
  • Save andynu/1477485 to your computer and use it in GitHub Desktop.
Save andynu/1477485 to your computer and use it in GitHub Desktop.
A array of hashes summing method
def sum_by(arr_hash, value_key, group_key=nil, &block)
if group_key.instance_of? Proc
block = group_key
group_key = nil
end
arr_hash.inject({}) do |sums, row|
group_key = (block_given?) ? block.call(row) : group_key
sums[group_key] ||= 0.0
sums[group_key] += row[value_key] || 0.0
sums
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment