On Tue, Mar 11, 2014 at 9:47 AM, Arup Rakshit <lists / ruby-forum.com> wrote:
> The below code is completely working :
>
> a = [{:a=>1},{:a=>10},{:b=>8},{:c=>7},{:c=>2}]
> merged_hash = a.each_with_object({})  do |item,hsh|
>   k,v = item.shift
>   hsh.has_key?(k) ? hsh[k] = [v] << hsh[k] : hsh[k] = v
> end
>
> merged_hash.map { |k,v| { k => v } }
> # => [{:a=>[10, 1]}, {:b=>8}, {:c=>[2, 7]}]
>
> But, Is it a expressive code or some tweak can still be applied on this
> ?

Although it's not exactly the same solution (single elements end up in
arrays too), I propose this:

2.0.0p195 :005 > a = [{:a=>1},{:a=>10},{:b=>8},{:c=>7},{:c=>2}]
 => [{:a=>1}, {:a=>10}, {:b=>8}, {:c=>7}, {:c=>2}]

2.0.0p195 :006 > merged_hash = Hash.new {|h,k| h[k] = []}
 => {}

2.0.0p195 :007 > a.each {|h| h.each {|k,v| merged_hash[k] << v}}
 => [{:a=>1}, {:a=>10}, {:b=>8}, {:c=>7}, {:c=>2}]

2.0.0p195 :008 > merged_hash
 => {:a=>[1, 10], :b=>[8], :c=>[7, 2]}

It might give you some ideas.

Jesus.