Method: Array#uniq
- Defined in:
- array.c
#uniq ⇒ Object #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 duplicate elements using method eql?
to compare elements:
a = [0, 0, 1, 1, 2, 2]
a.uniq # => [0, 1, 2]
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:
a = ['a', 'aa', 'aaa', 'b', 'bb', 'bbb']
a.uniq {|element| element.size } # => ["a", "aa", "aaa"]
Related: Methods for Fetching.
6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 |
# File 'array.c', line 6359
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);
}
return uniq;
}
|