Ruby uniq array method

In ruby programming language, uniq() method are remove duplicate elements and return new array which contains distinct elements. Syntax of this method as follows.

Syntax Array.uniq, Array.uniq(), Array.uniq{}
Block Optional,and block for comparison
Return New array

This method has two forms (uniq() and uniq!()). uniq!() method are modifying the actual array in place. Syntax of this method as follows.

Syntax Array.uniq!{}
Block Comparison
Return Reference of array, nil if no changes

Ruby uniq method example

In below example is based on a uniq() method. let's see examples to returning value.

# Example uniq()

# Test array
record1 = [1,15,2,[5,6],6,4,[5,6],15]
record2 = [3,4,3,1,1]

# uniq operation
a = record1.uniq
b = record2.uniq()

# Display array
print(" record1 ",record1)
print("\n record2 ",record2)

# Display result
print("\n a : ", a)
print("\n b : ", b)
Ruby uniq method example 1
 record1 [1, 15, 2, [5, 6], 6, 4, [5, 6], 15]
 record2 [3, 4, 3, 1, 1]
 a : [1, 15, 2, [5, 6], 6, 4]
 b : [3, 4, 1]
# Example 2 uniq()
# Test array
record = ["if","code","is","books","copy","bag","bord"]

# Test uniq
# Removes words that have the same length
data = record.uniq{|word| word.length()}

# Display array
print("\n record :",record)
print("\n  data :",data)

 record :["if", "code", "is", "books", "copy", "bag", "bord"]
  data :["if", "code", "books", "bag"]

Ruby uniq!() method example

This method are modifies actual array objects. in given below examples are mention.

 # Example uniq!()
# Test array
record1 = [1,15,2,[5,6],6,4,[5,6],15]
record2 = [3,4,3,1,1]

# Display array
print(" Before ");
print("\n record1 ",record1)
print("\n record2 ",record2)

# Test uniq!
record1.uniq!
record2.uniq!()

# Display array
print("\n After ");
print("\n record1 ",record1)
print("\n record2 ",record2)
Ruby uniq! method example 1
 Before 
 record1 [1, 15, 2, [5, 6], 6, 4, [5, 6], 15]
 record2 [3, 4, 3, 1, 1]
 After 
 record1 [1, 15, 2, [5, 6], 6, 4]
 record2 [3, 4, 1]
# Example 2 uniq!()
# Test array
record = ["if","code","is","books","copy","bag","bord"]

# Display array
print(" Before ");
print("\n record ",record)


# Test uniq!
# Removes words that have the same length
record.uniq!{|word| word.length()}


# Display array
print("\n After ");
print("\n record ",record)
Ruby uniq! method example 2
 Before 
 record ["if", "code", "is", "books", "copy", "bag", "bord"]
 After 
 record ["if", "code", "books", "bag"]


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved