Skip to content

Instantly share code, notes, and snippets.

@mdepolli
Last active December 14, 2015 08:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdepolli/5058534 to your computer and use it in GitHub Desktop.
Save mdepolli/5058534 to your computer and use it in GitHub Desktop.
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
Copy link

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}

@caffo
Copy link

caffo 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

@guipdutra
Copy link

Legal caffo, valeu !

@tinogomes
Copy link

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

@mdepolli
Copy link
Author

mdepolli commented Mar 1, 2013

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