Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group array of hashes by key

Tags:

arrays

ruby

I have an array consisting of hashes in the following form:

[
  {:user=>"mike" etc},
  {:user=>"mike" etc},
  {:user=>"peter" etc},
  {:user=>"joe" etc}
]

Are there any convenient ways to split the group according to the value of user key? The final result should be something like this:

[
  [{:user=>"mike" etc}, {:user=>"mike" etc}],
  [{:user=>"peter" etc}],
  [{:user=>"joe" etc}]
]
like image 860
Kert Avatar asked Jul 07 '13 14:07

Kert


1 Answers

Use group_by.

array.group_by{|h| h[:user]}.values
like image 185
sawa Avatar answered Nov 13 '22 23:11

sawa