Skip to content

Instantly share code, notes, and snippets.

@joaquimadraz
Last active August 29, 2015 14:21
Show Gist options
  • Save joaquimadraz/bb7dd653315049d6a06a to your computer and use it in GitHub Desktop.
Save joaquimadraz/bb7dd653315049d6a06a to your computer and use it in GitHub Desktop.
merge same key array of hashes
# input = [
# {:alarma=>{:foo2=>"bar2"}},
# {:alarma=>{:foo=>"bar"}},
# {:alarma=>{:test2=>{:foo=>"bar"}}},
# {:cenas=>"teste"},
# {:alarma=>{:foo2=>"bar2", :foo=>"bar"}}
# ]
input = [
{:foo=>{:foo=>{:bar=>"stuff"}}},
{:foo=>{:foo=>{:foo=>"bar"}}}
]
# based on: http://stackoverflow.com/questions/136793/is-there-a-do-while-loop-in-ruby
# array.group_by(&:keys).map{|k, v| {k.first => v.flat_map(&:values)}}
def squeeze_hash_array(ary)
ary
.group_by(&:keys)
.map do |k, v|
flat_values = v.flat_map(&:values)
{}.tap do |h|
h[k.first] = if flat_values.all?{|fv| fv.is_a?(Hash)}
squeeze_hash_array(flat_values)
else
flat_values[0]
end
end
end
.reduce(&:merge)
end
result = squeeze_hash_array(input)
puts result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment