How can I group this array of hashes?

后端 未结 3 1755
陌清茗
陌清茗 2021-02-01 02:12

I have this array of hashes:

- :name: Ben
  :age: 18
- :name: David
  :age: 19
- :name: Sam
  :age: 18

I need to group them by age

3条回答
  •  再見小時候
    2021-02-01 02:22

    The &:age means that the group_by method should call the age method on the array items to get the group by data. This age method is not defined on the items which are Hashes in your case.

    This should work:

    array.group_by { |d| d[:age] }
    

提交回复
热议问题