Nick Mart
Nick Mart

Reputation: 363

How to group identical elements in Ruby array

I have the following:

array = ["John", "Mike", "Bob", "Mike", "Bob"]

i want to get output:

[["Mike", "Mike"], ["Bob", "Bob"], ["John"]]

Upvotes: 29

Views: 17002

Answers (1)

sawa
sawa

Reputation: 168101

Here is how to do that in Ruby.

array.group_by{ |x| x }.values

Upvotes: 55

Related Questions