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
array.c
View on GitHub ↗
static VALUE
rb_ary_uniq_bang(VALUE ary)
{
rb_ary_modify_check(ary);
if (RARRAY_LEN(ary) <= 1)
return Qnil;
if (rb_block_given_p()) {
VALUE set = rb_obj_hide(rb_set_new_capa(RARRAY_LEN(ary)));
VALUE uniq = rb_ary_new_capa(RARRAY_LEN(ary));
for (rb_len_t i = 0; i < RARRAY_LEN(ary); i++) {
VALUE elt = rb_ary_elt(ary, i);
if (rb_set_add_no_check(set, rb_yield(elt)))
rb_ary_push(uniq, elt);
}
if (RARRAY_LEN(ary) == RARRAY_LEN(uniq))
return Qnil;
rb_ary_replace(ary, uniq);
return ary;
}
VALUE set = ary_to_set(ary);
rb_len_t size = (rb_len_t)rb_set_size(set);
if (RARRAY_LEN(ary) == size) {
return Qnil;
}
rb_ary_modify_check(ary);
ARY_SET_LEN(ary, 0);
if (ARY_SHARED_P(ary)) {
rb_ary_unshare(ary);
FL_SET_EMBED(ary);
}
ary_resize_capa(ary, size);
rb_set_foreach(set, push_value_i, ary);
return ary;
}
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.