Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
instance method
Array#&
(::array[untyped] other_array) -> ::Array[Elem]
self & other_array → new_array
array.c
View on GitHub ↗
static VALUE
rb_ary_and(VALUE ary1, VALUE ary2)
{
ary2 = to_ary(ary2);
VALUE ary3 = rb_ary_new();
if (RARRAY_LEN(ary1) == 0 || RARRAY_LEN(ary2) == 0) return ary3;
if (RARRAY_LEN(ary1) <= SMALL_ARRAY_LEN && RARRAY_LEN(ary2) <= SMALL_ARRAY_LEN) {
for (rb_len_t i = 0; i < RARRAY_LEN(ary1); i++) {
VALUE v = RARRAY_AREF(ary1, i);
if (!rb_ary_includes_by_eql(ary2, v)) continue;
if (rb_ary_includes_by_eql(ary3, v)) continue;
rb_ary_push(ary3, v);
}
return ary3;
}
VALUE set = ary_to_set(ary2);
for (rb_len_t i = 0; i < RARRAY_LEN(ary1); i++) {
VALUE v = RARRAY_AREF(ary1, i);
if (rb_set_delete_no_check(set, v)) {
rb_ary_push(ary3, v);
}
}
return ary3;
}
Returns a new array containing the intersection of self and other_array; that is, containing those elements found in both self and other_array:
Example
[0, 1, 2, 3] & [1, 2] # => [1, 2]
Omits duplicates:
Example
[0, 1, 1, 0] & [0, 1] # => [0, 1]
Preserves order from self:
Example
[0, 1, 2] & [3, 2, 1, 0] # => [0, 1, 2]
Identifies common elements using method eql? (as defined in each element of self).
Related: see Methods for Combining.