Open In App

Ruby | Enumerator::Lazy#uniq function

The uniq function in Ruby is used to find the unique set of elements from the given array.

Syntax: xs.uniq
Here, xs is a array of elements.



Parameters: This function does not accept any parameters.

Returns: the new set of unique values.



Example 1:




# Initialising an array with blocks as elements
xs = [ [1, "GFG", 10], [1, "GFG", 20], 
    [2, "Geeks", 30], [2, "Geeks", 40] ].to_enum.lazy
   
# Calling uniq function for finding uniq element block
us = xs.uniq{ |x| x[0] }.map{ |x| [x[0], x[1]] }
   
# Produces result in blocks
puts us.to_a.inspect

Output:

[[1, "GFG"], [2, "Geeks"]]

Example 2:




# Initialising an array
ns = [1, 4, 6, 1, 2].to_enum.lazy
  
# calling the uniq function for finding 
# uniq values form the above array
puts ns.uniq.to_a.inspect

Output:

[1, 4, 6, 2]
Article Tags :