Get unique array elements
suggest changeTo read an array’s elements without repetitions, use uniq:
a = [1, 1, 2, 3, 4, 4, 5]
a.uniq
#=> [1, 2, 3, 4, 5]
To remove duplicates from the array itself, use uniq!:
a = [1, 1, 2, 3, 4, 4, 5]
a.uniq!
#=> [1, 2, 3, 4, 5]
uniq returns a new array and leaves the receiver alone. uniq! changes the receiver and returns it, or returns nil if nothing was removed:
a = [1, 1, 2, 3, 4, 4, 5]
a.uniq
#=> [1, 2, 3, 4, 5]
a
#=> [1, 1, 2, 3, 4, 4, 5]
a = [1, 1, 2, 3, 4, 4, 5]
a.uniq!
#=> [1, 2, 3, 4, 5]
a
#=> [1, 2, 3, 4, 5]
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents