Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group identical elements in Ruby array

Tags:

arrays

ruby

I have the following:

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

i want to get output:

[["Mike", "Mike"], ["Bob", "Bob"], ["John"]] 
like image 732
Nick Mart Avatar asked Oct 04 '12 10:10

Nick Mart


People also ask

How do I group an array in Ruby?

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" .

What does .shift do in Ruby?

The shift() is an inbuilt function in Ruby returns the element in the front of the SizedQueue and removes it from the SizedQueue. Parameters: The function does not takes any element.

Are Ruby arrays homogeneous?

A Ruby array is heterogeneous in the sense that it can store multiple data types rather than just one type. Actually, it stores object references rather than the objects themselves, except in the case of immediate values such as Fixnum values.

How does group by work in Ruby?

The group_by() of enumerable is an inbuilt method in Ruby returns an hash where the groups are collectively kept as the result of the block after grouping them. In case no block is given, then an enumerator is returned. Parameters: The function takes an optional block according to which grouping is done.


1 Answers

Here is how to do that in Ruby.

array.group_by{ |x| x }.values 
like image 67
sawa Avatar answered Sep 25 '22 13:09

sawa