Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 can't modify it to leave just the name and not the full hash. I need to do this in one line because is for a grouped_options_for_select on a Rails form.

like image 950
jtomasrl Avatar asked Sep 20 '13 15:09

jtomasrl


2 Answers

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"]}
like image 75
sawa Avatar answered Oct 14 '22 13:10

sawa


In a single iteration over initial array:

arry.inject(Hash.new([])) { |h, a| h[a[:type]] += [a[:name]]; h }
like image 32
Nikita Chernov Avatar answered Oct 14 '22 13:10

Nikita Chernov