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 } } |
Mas fazer isso é tão bom!
Perceba que a minha solução tem os espaços dentro do bloco, isso precisa ser levado em consideração. Pessoas que usam bloco sem espaços não merecem ocupar um lugar no planeta. cough cough
@mdepolli dei uma refatorada na sua solução.
a.inject({}) { |marypoppins, superman| marypoppins.merge(superman) { |god, asterix, obelix| asterix + obelix } }
tapa não use deus como nome de variavel local, ou os crentes vão te matar! deus tem que ser CONSTANTE
You win, sir. 👏
Tou rindo muito aqui :)
MARY_POPPINS = 42
Assim?
tem alguma diferença ?
response = Hash.new(0)
response = {}
b = {"foo" => 100, "bar" => 300, "zaz" => 5}
c = {"foo" => 200, "bar" => 8}
a = [b, c]
d = a.inject(Hash.new(0)) do |memo, element|
element.each_pair do |key, value|
memo[key] += value
end
memo
end
puts d.inspect
# => {"foo" => 300, "bar" => 308, "zaz" => 5}
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
Você e o @caffo estão sem nada melhor para fazer? :-)