Ruby array of hash. group_by and modify in one line Ruby array of hash. group_by and modify in one line ruby ruby

Ruby array of hash. group_by and modify in one line


array.group_by{|h| h[:type]}.each{|_, v| v.replace(v.map{|h| h[:name]})}# => {"Meat"=>["one", "two"], "Fruit"=>["four"]}

Following steenslag's suggestion:

array.group_by{|h| h[:type]}.each{|_, v| v.map!{|h| h[:name]}}# => {"Meat"=>["one", "two"], "Fruit"=>["four"]}


In a single iteration over initial array:

arry.inject(Hash.new([])) { |h, a| h[a[:type]] += [a[:name]]; h }


Using ActiveSuport's Hash#transform_values:

array.group_by{ |h| h[:type] }.transform_values{ |hs| hs.map{ |h| h[:name] } }#=> {"Meat"=>["one", "two"], "Fruit"=>["four"]}