Ruby array of hash. group_by and modify in one line

后端 未结 6 1426
不知归路
不知归路 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

    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"]}
    

提交回复
热议问题