Method: Array#uniq

Defined in:
array.c

#uniqObject #uniq {|element| ... } ⇒ Object

Returns a new Array containing those elements from self that are not duplicates, the first occurrence always being retained.

With no block given, identifies and omits duplicates using method eql? to compare.

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

With a block given, calls the block for each element; identifies (using method eql?) and omits duplicate values, that is, those elements for which the block returns the same value:

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

Overloads:

  • #uniq {|element| ... } ⇒ Object

    Yields:

    • (element)


6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
# File 'array.c', line 6002

static VALUE
rb_ary_uniq(VALUE ary)
{
    VALUE hash, uniq;

    if (RARRAY_LEN(ary) <= 1) {
        hash = 0;
        uniq = rb_ary_dup(ary);
    }
    else if (rb_block_given_p()) {
	hash = ary_make_hash_by(ary);
	uniq = rb_hash_values(hash);
    }
    else {
	hash = ary_make_hash(ary);
	uniq = rb_hash_values(hash);
    }
    if (hash) {
        ary_recycle_hash(hash);
    }

    return uniq;
}