Last active
December 14, 2015 08:29
-
-
Save mdepolli/5058534 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
b = {"foo" => 100, "bar" => 300, "zaz" => 5} | |
c = {"foo" => 200, "bar" => 8} | |
a = [b, c] | |
# ??? = {"foo" => 300, "bar" => 308, "zaz" = 5} | |
# Solução caffo 1 | |
response = Hash.new(0) | |
a.each {|i| i.each {|key, val| response[key] += val} } | |
# Solução caffo 2 | |
a.inject(Hash.new(0)){|memo, i| i.each {|key, val| memo[key] += val }; memo} | |
# Solução depa | |
a.inject({}) { |sum, ele| sum.merge(ele) { |key, first, second| first + second } } |
sobrinho
commented
Feb 28, 2013
1.9.3-p194 :003 > a=Hash.new(0)
=> {}
1.9.3-p194 :004 > a[:foo]
=> 0
1.9.3-p194 :006 > a = {}
=> {}
1.9.3-p194 :007 > a[:foo]
=> nil
Legal caffo, valeu !
Inspirado na implementação do @mdepolli
module SumHash
def sum(another)
self.merge(another) {|key, current, value| current + value }
end
end
Hash.__send__ :include, SumHash
b = {"foo" => 100, "bar" => 300, "zaz" => 5}
c = {"foo" => 200, "bar" => 8}
a = [b, c]
a.inject :sum
Pessoal, tá faltando uma implementação usando refinements e keyword arguments!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment