instance method
Array#uniq!
() -> self?
() { (Elem) -> untyped } -> self?
uniq! → self or nil
uniq! {|element| ... } → self or nil
array.c
View on GitHub ↗
static VALUE
rb_ary_uniq_bang(VALUE ary)
{
VALUE hash;
long hash_size;
rb_ary_modify_check(ary);
if (RARRAY_LEN(ary) <= 1)
return Qnil;
if (rb_block_given_p())
hash = ary_make_hash_by(ary);
else
hash = ary_make_hash(ary);
hash_size = RHASH_SIZE(hash);
if (RARRAY_LEN(ary) == hash_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, hash_size);
rb_hash_foreach(hash, push_value, 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? 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? 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.