Skip to content

Instantly share code, notes, and snippets.

@ohnishiakira
Last active January 2, 2016 13:49
Show Gist options
  • Save ohnishiakira/8312484 to your computer and use it in GitHub Desktop.
Save ohnishiakira/8312484 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# coding: utf-8
hash = [
{hoge: {fuga: 3}},
{hoge: {homu: 5}},
{fuga: {hoge: 4}},
{fuga: {pero: 6}}
]
hash1 = hash.group_by{|h| h.keys}
.map{|k,arr|
{k.first => arr.map{|a| a.values}.flatten.inject(:merge)}
}.inject(:merge)
p hash1
#=> {:hoge=>{:fuga=>3, :homu=>5}, :fuga=>{:hoge=>4, :pero=>6}}
require "active_support/core_ext"
p hash.inject({}){|ha, h| ha.deep_merge(h)}
#=> {:hoge=>{:fuga=>3, :homu=>5}, :fuga=>{:hoge=>4, :pero=>6}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment