I need a group an array of hashes based on a particular key of each hash. For example, take this:
[
[0] {
:status => "pending",
:x => 1,
:y => 2
},
[1] {
:status => "pending",
:x => 33,
:y => 74
},
[2] {
:status => "done",
:x => 33,
:y => 74
}
]
I need to convert it to this:
{
"pending" => [
[0] {
:status => "pending",
:x => 1,
:y => 2
},
[1] {
:status => "pending",
:x => 33,
:y => 74
}
],
"done" => [
[0] {
:status => "done",
:x => 33,
:y => 74
}
]
}
I am grouping the array by :status key. I have done this (it works):
a.inject({}) {|a, b| (a[b[:status]] ||= []) << b; a }
But, is there a simpler, less cryptic one-liner that can do the same thing?