From 55d91a096a840aaff1e08a4286c216da56b6e968 Mon Sep 17 00:00:00 2001 From: Travis Hunter Date: Wed, 3 Oct 2018 15:19:36 -0400 Subject: [PATCH] Add Array#intersect? --- array.c | 56 +++++++++++++++++++++++++++++++++++++++++ test/ruby/test_array.rb | 13 ++++++++++ 2 files changed, 69 insertions(+) diff --git a/array.c b/array.c index be744e2983..f97be64655 100644 --- a/array.c +++ b/array.c @@ -5567,6 +5567,61 @@ rb_ary_union_multi(int argc, VALUE *argv, VALUE ary) return ary_union; } +/* + * call-seq: + * ary.intersect?(other_ary) -> true or false + * + * Returns +true+ if the array and +other_ary+ have at least one element in + * common, otherwise returns +false+. + * + * a = [ 1, 2, 3 ] + * b = [ 3, 4, 5 ] + * c = [ 5, 6, 7 ] + * a.intersect?(b) #=> true + * a.intersect?(c) #=> false + */ + +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(ary2)) { + longer = ary1; + shorter = ary2; + } + + hash = ary_make_hash(shorter); + result = Qfalse; + + for (i=0; i