How can I group this array of hashes?

后端 未结 3 1833
陌清茗
陌清茗 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:16

    As others have pointed out ruby's Symbol#to_proc method is invoked and calls the age method on each hash in the array. The problem here is that the hashes do not respond to an age method.

    Now we could define one for the Hash class, but we probably don't want it for every hash instance in the program. Instead we can simply define the age method on each hash in the array like so:

    array.each do |hash|
      class << hash
        def age
          self[:age]
        end
      end
    end
    

    And then we can use group_by just as you were before:

    array = array.group_by &:age
    

提交回复
热议问题