Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

instance method

Array#uniq!

() -> self?
() { (Elem element) -> ::Hash::_Key } -> self?
uniq! → self or nil
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? and hash to compare elements:

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

With a block given, calls the block for each element; identifies and omits “duplicate” elements using method eql? and hash to compare block return values; that is, an element is a duplicate if its block return value is the same as that of a previous element:

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

Related: see Methods for Deleting.

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