Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
instance method
Array#uniq
() -> ::Array[Elem]
() { (Elem element) -> ::Hash::_Key } -> ::Array[Elem]
uniq → new_array
uniq {|element| ... } → new_array
array.c
View on GitHub ↗
static VALUE
rb_ary_uniq(VALUE ary)
{
if (RARRAY_LEN(ary) <= 1) {
return rb_ary_dup(ary);
}
VALUE set = rb_obj_hide(rb_set_new_capa(RARRAY_LEN(ary)));
if (rb_block_given_p()) {
VALUE uniq = rb_ary_new_capa(RARRAY_LEN(ary));
for (rb_len_t i = 0; i < RARRAY_LEN(ary); i++) {
VALUE elt = rb_ary_elt(ary, i);
if (rb_set_add_no_check(set, rb_yield(elt)))
rb_ary_push(uniq, elt);
}
return uniq;
}
else {
rb_ary_union_set(set, ary);
return rb_set_to_a(set);
}
}
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? and hash to compare elements:
Example
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? and hash 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"]
Related: Methods for Fetching.