Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 901
ben Avatar asked Aug 21 '11 07:08

ben


People also ask

How do I group an array in Ruby?

The group by creates a hash from the capitalize d version of an album name to an array containing all the strings in list that match it (e.g. "Enter sandman" => ["Enter Sandman", "Enter sandman"] ). The map then replaces each array with its length, so you get e.g. ["Enter sandman", 2] for "Enter sandman" .

What is hash array?

An array of hashes is useful when you have a bunch of records that you'd like to access sequentially, and each record itself contains key/value pairs. Arrays of hashes are used less frequently than the other structures in this chapter.

What is the difference between hashes and arrays?

With arrays, the key is an integer, whereas hashes support any object as a key. Both arrays and hashes grow as needed to hold new elements. It's more efficient to access array elements, but hashes provide more flexibility.

How do you turn an array into a hash?

The to_h method is defined in the array class. It works to convert an array to a hash in the form of key-value pairs. The method converts each nested array into key-value pairs. The method also accepts a block.


1 Answers

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] } 
like image 101
KARASZI István Avatar answered Sep 18 '22 13:09

KARASZI István