Last active
November 8, 2015 00:47
-
-
Save nullset2/7201f2c4cde76ede9a54 to your computer and use it in GitHub Desktop.
Summing values from Bidimensional hash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#see http://nullset2.tumblr.com/post/132761268939/a-quick-recipe-with-hashes | |
data = { :A => { :D => 100, :E => 200, :F => 300}, :B => { :G => 10, :H => 20, :I => 30 }, :C => { :J => 1, :K => 2, :L => 3 } } | |
# => {:A=>{:D=>100, :E=>200, :F=>300}, :B=>{:G=>10, :H=>20, :I=>30}, :C=>{:J=>1, :K=>2, :L=>3}} | |
# data = Hash.new { |k, v| k[v] = Hash.new { |kk, vv| kk[vv] = 0 } } # or you could also initialize that shit like this, then assign stuff to each key-value pair individually | |
vals = data.map do |k, v| # saving the sums elsewhere temporarily | |
v.values.reduce(&:+) #sum the corresponding values to ALL the elements in the "second dimension" of this hash, per first dimension key | |
end | |
# => [600, 60, 6] | |
#then we marry both of these into an array: | |
data = Hash[data.keys.zip vals] | |
# => {:A=>600, :B=>60, :C=>6} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment