Skip to content

Instantly share code, notes, and snippets.

@xcobar

xcobar/sum.rb Secret

Last active March 25, 2020 16:31
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 xcobar/22164664b1255aed43e134758449577d to your computer and use it in GitHub Desktop.
Save xcobar/22164664b1255aed43e134758449577d to your computer and use it in GitHub Desktop.
array = [
{
cars: 4,
houses: 5,
job: {},
fat: {},
},
{
cars: 4,
houses: 5,
job: {},
fat: {},
},
{
cars: 4,
houses: 5,
job: {},
fat: {},
},
]
#array = array.reduce(Hash.new(0)) { |acc, h| acc.merge(h) { |_key, left, right| left + right } }
first, *rest = array
first.merge(*rest) { |key, left, right| left + right unless %i[job fat].include?(key) }.compact
p array
#=> [{:cars=>4, :houses=>5, :job=>{}, :fat=>{}}, {:cars=>4, :houses=>5, :job=>{}, :fat=>{}}, {:cars=>4, :houses=>5, :job=>{}, :fat=>{}}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment