Skip to content

Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →

instance method

Array#uniq!

array.uniq! → self or nil
array.uniq! {|element| ... } → self or nil

Removes duplicate elements from self, the first occurrence always being retained; returns self if any elements removed, nil otherwise.

With no block given, identifies and removes elements using method eql? to compare.

Returns self if any elements removed:

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

Returns nil if no elements removed.

With a block given, calls the block for each element; identifies (using method eql?) and removes elements for which the block returns duplicate values.

Returns self if any elements removed:

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

Returns nil if no elements removed.

See also #uniq #unshift #union #values_at also in 4.1 · 4.0 · 3.4 · 3.2 · 3.1 · 3.0