Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
instance method · added in Ruby 3.1
Array#intersect?
(::array[untyped] other_array) -> bool
intersect?(other_array) → true or false
array.c
View on GitHub ↗
static VALUE
rb_ary_intersect_p(VALUE ary1, VALUE ary2)
{
ary2 = to_ary(ary2);
if (RARRAY_LEN(ary1) == 0 || RARRAY_LEN(ary2) == 0) return Qfalse;
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)) return Qtrue;
}
return Qfalse;
}
VALUE shorter = ary1;
VALUE longer = ary2;
if (RARRAY_LEN(ary1) > RARRAY_LEN(ary2)) {
longer = ary1;
shorter = ary2;
}
VALUE set = ary_to_set(shorter);
VALUE result = Qfalse;
for (rb_len_t i = 0; i < RARRAY_LEN(longer); i++) {
VALUE v = RARRAY_AREF(longer, i);
if (rb_set_lookup(set, v)) {
result = Qtrue;
break;
}
}
return result;
}
Returns whether other_array has at least one element that is eql? to some element of self:
Example
[1, 2, 3].intersect?([3, 4, 5]) # => true [1, 2, 3].intersect?([4, 5, 6]) # => false
Each element must correctly implement method hash.
Related: see Methods for Querying.
Ruby version changes
-
3.1
-
Array#intersect?is added. [Feature #15198]
-