ruby-on-railsrubyruby-on-rails-3group-by

How can I group this array of hashes?


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, so they end up like this:

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

I tried doing it this way:

array = array.group_by &:age

but I get this error:

NoMethodError (undefined method `age' for {:name=>"Ben", :age=>18}:Hash):

What am I doing wrong? I'm using Rails 3.0.1 and Ruby 1.9.2


Solution

  • 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 that are Hashes in your case.

    This should work:

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

    Also with newer Ruby versions you can use the following shortcut:

    array.group_by { _1[:age] }
    

    _1 here reflects the first positional argument of the block passed to the #group_by method.