Ruby Newbie homepage Ruby Newbie homepage

How to use

Quick guide

Official content
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:
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:
a = ['a', 'aa', 'aaa', 'b', 'bb', 'bbb']
a.uniq! {|element| element.size } # => ['a', 'aa', 'aaa']
Returns nil if no elements removed.
               static VALUE
rb_ary_uniq_bang(VALUE ary)
    VALUE hash;
    long hash_size;

    if (RARRAY_LEN(ary) <= 1)
        return Qnil;
    if (rb_block_given_p())
        hash = ary_make_hash_by(ary);
        hash = ary_make_hash(ary);

    hash_size = RHASH_SIZE(hash);
    if (RARRAY_LEN(ary) == hash_size) {
        return Qnil;
    ARY_SET_LEN(ary, 0);
    if (ARY_SHARED_P(ary) && !ARY_EMBED_P(ary)) {
    ary_resize_capa(ary, hash_size);
    rb_hash_foreach(hash, push_value, ary);

    return ary;

Was this page useful?