uniq!()
public
Removes duplicate elements from self. If a block is given, it will
use the return value of the block for comparison. Returns nil if no changes
are made (that is, no duplicates are found).
a = [ "a", "a", "b", "b", "c" ]
a.uniq!
b = [ "a", "b", "c" ]
b.uniq!
c = [["student","sam"], ["student","george"], ["teacher","matz"]]
c.uniq! { |s| s.first }
Show source
static VALUE
rb_ary_uniq_bang(VALUE ary)
{
VALUE hash, v;
long i, j;
rb_ary_modify_check(ary);
if (RARRAY_LEN(ary) <= 1)
return Qnil;
if (rb_block_given_p()) {
hash = ary_make_hash_by(ary);
if (RARRAY_LEN(ary) == (i = RHASH_SIZE(hash))) {
return Qnil;
}
ARY_SET_LEN(ary, 0);
if (ARY_SHARED_P(ary) && !ARY_EMBED_P(ary)) {
rb_ary_unshare(ary);
FL_SET_EMBED(ary);
}
ary_resize_capa(ary, i);
st_foreach(RHASH_TBL(hash), push_value, ary);
}
else {
hash = ary_make_hash(ary);
if (RARRAY_LEN(ary) == (long)RHASH_SIZE(hash)) {
return Qnil;
}
for (i=j=0; i<RARRAY_LEN(ary); i++) {
st_data_t vv = (st_data_t)(v = rb_ary_elt(ary, i));
if (st_delete(RHASH_TBL(hash), &vv, 0)) {
rb_ary_store(ary, j++, v);
}
}
ARY_SET_LEN(ary, j);
}
ary_recycle_hash(hash);
return ary;
}