Ruby array of hash. group_by and modify in one line

后端 未结 6 1403
不知归路
不知归路 2020-12-31 04:07

I have an array of hashes, something like

[ {:type=>\"Meat\", :name=>\"one\"}, 
  {:type=>\"Meat\", :name=>\"two\"}, 
  {:type=>\"Fruit\", :n         


        
6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-31 04:53

    I would do as below :

    hsh =[{:type=>"Meat", :name=>"one"}, {:type=>"Meat", :name=>"two"}, {:type=>"Fruit", :name=>"four"}]
    p Hash[hsh.group_by{|h| h[:type] }.map{|k,v| [k,v.map{|h|h[:name]}]}]
    
    # >> {"Meat"=>["one", "two"], "Fruit"=>["four"]}
    

提交回复
热议问题