Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
instance method
Array#difference
(*::array[untyped] other_arrays) -> ::Array[Elem]
difference(*other_arrays = []) → new_array
array.c
View on GitHub ↗
static VALUE
rb_ary_difference_multi(int argc, VALUE *argv, VALUE ary)
{
volatile VALUE t0;
bool *is_set = ALLOCV_N(bool, t0, argc);
VALUE ary_diff = rb_ary_new();
rb_len_t length = RARRAY_LEN(ary);
for (rb_len_t i = 0; i < argc; i++) {
argv[i] = to_ary(argv[i]);
is_set[i] = (length > SMALL_ARRAY_LEN && RARRAY_LEN(argv[i]) > SMALL_ARRAY_LEN);
if (is_set[i]) {
argv[i] = ary_to_set(argv[i]);
}
}
for (rb_len_t i = 0; i < RARRAY_LEN(ary); i++) {
int j;
VALUE elt = rb_ary_elt(ary, i);
for (j = 0; j < argc; j++) {
if (is_set[j]) {
if (rb_set_lookup(argv[j], elt))
break;
}
else {
if (rb_ary_includes_by_eql(argv[j], elt)) break;
}
}
if (j == argc) rb_ary_push(ary_diff, elt);
}
ALLOCV_END(t0);
return ary_diff;
}
Returns a new array containing only those elements from self that are not found in any of the given other_arrays; items are compared using eql?; order from self is preserved:
Example
[0, 1, 1, 2, 1, 1, 3, 1, 1].difference([1]) # => [0, 2, 3] [0, 1, 2, 3].difference([3, 0], [1, 3]) # => [2] [0, 1, 2].difference([4]) # => [0, 1, 2] [0, 1, 2].difference # => [0, 1, 2]
Returns a copy of self if no arguments are given.
Related: Array#-; see also Methods for Combining.