Skip to content

Instantly share code, notes, and snippets.

@duykhoa
Last active August 29, 2015 14:22
Show Gist options
  • Save duykhoa/ff229b8c38574a18c0c9 to your computer and use it in GitHub Desktop.
Save duykhoa/ff229b8c38574a18c0c9 to your computer and use it in GitHub Desktop.
hash group
a = [{:id=>1, :phone=>2}, {:id=>1, :phone=>3}, {:id=>2, :phone=>2}]
a.group_by { |item| item[:id] }
{1=>[{:id=>1, :phone=>2}, {:id=>1, :phone=>3}], 2=>[{:id=>2, :phone=>2}]}
b = _[1]
[{:id=>1, :phone=>2}, {:id=>1, :phone=>3}]
b.map { |h| h[:phone] }
[2, 3]
# so combine everything
a.group_by { |h| h[:id] }.map { |id, hs| { id: id, phone: hs.map { |h| h[:phone] }} }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment