Skip to content

End of Life Ruby 3.2 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

Array#uniq

array.uniq → new_array
array.uniq {|element| ... } → new_array

Returns a new Array containing those elements from self that are not duplicates, the first occurrence always being retained.

With no block given, identifies and omits duplicates using method eql? to compare:

Example
a = [0, 0, 1, 1, 2, 2]
a.uniq # => [0, 1, 2]

With a block given, calls the block for each element; identifies (using method eql?) and omits duplicate values, that is, those elements for which the block returns the same value:

Example
a = ['a', 'aa', 'aaa', 'b', 'bb', 'bbb']
a.uniq {|element| element.size } # => ["a", "aa", "aaa"]

Ruby version changes

  1. 3.0
See also #uniq! #union #transpose #unshift also in 4.1 · 4.0 · 3.4 · 3.3 · 3.1 · 3.0