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
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" .
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.
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.
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.
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] }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With