jtomasrl jtomasrl - 1 year ago 95
Ruby Question

Ruby array of hash. group_by and modify in one line

I have an array of hashes, something like

[{:type=>"Meat", :name=>"one"}, {:type=>"Meat", :name=>"two"}, {:type=>"Fruit", :name=>"four"}]

and i want to convert it to this

{ "Meat" => ["one", "two"], "Fruit" => ["Four"]}

I tried group_by but then i got this

{ "Meat" => [{:type=>"Meat", :name=>"one"}, {:type=>"Meat", :name=>"two"}], "Fruit" => [{:type=>"Fruit", :name=>"four"}]}

and then i cont modify it to leave just the name and not the full hash. I need to do this in one line becouse is for a "grouped_options_for_select" on a rails form

Answer Source
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"]}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download