Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →
instance method · added in Ruby 3.1
Array#intersect?
ary.intersect?(other_ary) → true or false
array.c
View on GitHub ↗
static VALUE
rb_ary_intersect_p(VALUE ary1, VALUE ary2)
{
VALUE hash, v, result, shorter, longer;
st_data_t vv;
long i;
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 (i=0; i<RARRAY_LEN(ary1); i++) {
v = RARRAY_AREF(ary1, i);
if (rb_ary_includes_by_eql(ary2, v)) return Qtrue;
}
return Qfalse;
}
shorter = ary1;
longer = ary2;
if (RARRAY_LEN(ary1) > RARRAY_LEN(ary2)) {
longer = ary1;
shorter = ary2;
}
hash = ary_make_hash(shorter);
result = Qfalse;
for (i=0; i<RARRAY_LEN(longer); i++) {
v = RARRAY_AREF(longer, i);
vv = (st_data_t)v;
if (rb_hash_stlike_lookup(hash, vv, 0)) {
result = Qtrue;
break;
}
}
return result;
}
Returns true if the array and other_ary have at least one element in common, otherwise returns false:
Example
a = [ 1, 2, 3 ] b = [ 3, 4, 5 ] c = [ 5, 6, 7 ] a.intersect?(b) #=> true a.intersect?(c) #=> false
Array elements are compared using eql? (items must also implement hash correctly).
Ruby version changes
-
3.1
-
Array#intersect?is added. [Feature #15198]
-