I have this array of pairs:
[{"a"=>"1"}, {"b"=>"2"}, {"a"=>"3"}, {"b"=>"4"}, {"a"=>"5"}]
I would like a method to merge the keys in common with multiple values 开发者_JAVA技巧to:
[{"a"=>["1","3","5"]}, {"b"=>["2","4"]}]
Improved following Marc-Andre's suggestion.
array = [{"a"=>"1"}, {"b"=>"2"}, {"a"=>"3"}, {"b"=>"4"}, {"a"=>"5"}]
array.group_by(&:keys).map{|k, v| {k.first => v.flat_map(&:values)}}
Or
array.group_by{|h| h.keys.first}.each_value{|a| a.map!{|h| h.values.first}}
Haven't tried it yet, but something like that should also works
a.each_with_object( Hash.new{ |h,k| h[k] = [] } ) do |x, hash|
hash[x.keys.first] << x.values.first
end
edit: For a one liner, and the same output :
[a.each_with_object( Hash.new{ |h,k| h[k] = [] } ) { |x, hash| hash[x.keys.first] << x.values.first }]
A solution to your problem:
array.map(&:first).group_by(&:first).map{|k, v| {k => v.map(&:last)}}
I'm curious as to why you start and end with hashes containing only one key-pair. Arrays would be better suited. E.g.:
other = [["a", "1"], ["b", "2"], ["a", "3"], ["b", "4"], ["a", "5"]]
r = other.group_by(&:first).map{|k, v| [k => v.map(&:last)]}
r # => [["a", ["1", "3", "5"]], ["b", ["2", "4"]]]
Hash[r] # => {"a"=>["1", "3", "5"], "b"=>["2", "4"]}
array = [{"a"=>"1"}, {"b"=>"2"}, {"a"=>"3"}, {"b"=>"4"}, {"a"=>"5"}]
{}.tap{ |r| array.each{ |h| h.each{ |k,v| (r[k]||=[]) << v } } }
Not sure if you're giving out awards for brevity, but I like this way. The merge function with a block is ideally suited for this:
new = {}
array.each {|p| new.merge!(p) {|k,l,r| [l,r].flatten }}
精彩评论