Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the unique elements in an array in Ruby

Tags:

arrays

ruby

I have an array with some elements. How can I get the number of occurrences of each element in the array?

For example, given:

a = ['cat', 'dog', 'fish', 'fish'] 

The result should be:

a2 #=> {'cat' => 1, 'dog' => 1, 'fish' => 2} 

How can I do that?

like image 248
Peter Becker Avatar asked May 02 '11 13:05

Peter Becker


People also ask

How do you find unique elements in an array?

By using hashmap's key. In Java, the simplest way to get unique elements from the array is by putting all elements of the array into hashmap's key and then print the keySet(). The hashmap contains only unique keys, so it will automatically remove that duplicate element from the hashmap keySet.

What does .first do in Ruby?

The first() is an inbuilt method in Ruby returns an array of first X elements. If X is not mentioned, it returns the first element only. Parameters: The function accepts X which is the number of elements from the beginning. Return Value: It returns an array of first X elements.

What does .last do in Ruby?

The . last property of an array in Ruby returns the last element of the array.


2 Answers

You can use Enumerable#group_by to do this:

res = Hash[a.group_by {|x| x}.map {|k,v| [k,v.count]}] #=> {"cat"=>1, "dog"=>1, "fish"=>2} 
like image 178
RameshVel Avatar answered Oct 11 '22 16:10

RameshVel


a2 = a.reduce(Hash.new(0)) { |a, b| a[b] += 1; a } #=> {"cat"=>1, "fish"=>2, "dog"=>1} 
like image 40
wallerdev Avatar answered Oct 11 '22 17:10

wallerdev