Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
communitycreator

What is array.uniq in Ruby?

okwudili onyejiaku

uniq is a Ruby method that returns a new array by removing duplicate elements or values of the array. The array is traversed in order and the first occurrence is kept.

Syntax

array.uniq

Parameters

uniq does not take any parameters; it is only called on an array.

Example

In the example below, several arrays are created. The arrays have duplicate elements in them, so we call the uniq method on them and return their values.

# create arrays
array1 = [1, 2, 3, 3, 4, 2, 1, 5]
array2 = ["a", "b", "a", "c", "d", "c", "e", "f", ]
array3 = [true, false, true, false, nil]
array4 = ["Cat", "Python", "Python", "Cat"]

# call the ".uniq" method on the arrays
a = array1.uniq
b = array2.uniq
c = array3.uniq
d = array4.uniq

# print values to the console
puts "Unique value of #{array1} = #{a}"
puts "Unique value of #{array2} = #{b}"
puts "Unique value of #{array3} = #{c}"
puts "Unique value of #{array4} = #{d}"

RELATED TAGS

ruby
communitycreator
RELATED COURSES

View all Courses

Keep Exploring