From 737254588b272ea898ebddd9fc4307fa555ddc35 Mon Sep 17 00:00:00 2001 From: "Yukihiro \"Matz\" Matsumoto" Date: Sat, 17 Apr 2021 17:38:44 +0900 Subject: array.rb: add `Array#intersect?` from Ruby3.0.1. --- mrbgems/mruby-array-ext/mrblib/array.rb | 41 +++++++++++++++++++++++++++++++++ mrbgems/mruby-array-ext/test/array.rb | 8 +++++++ 2 files changed, 49 insertions(+) (limited to 'mrbgems/mruby-array-ext') diff --git a/mrbgems/mruby-array-ext/mrblib/array.rb b/mrbgems/mruby-array-ext/mrblib/array.rb index 0195a6970..becfcb3ca 100644 --- a/mrbgems/mruby-array-ext/mrblib/array.rb +++ b/mrbgems/mruby-array-ext/mrblib/array.rb @@ -191,6 +191,47 @@ class Array ary end + ## + # 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 + def intersect?(ary) + raise TypeError, "can't convert #{ary.class} into Array" unless ary.class == Array + + hash = {} + if self.length > ary.length + shorter = ary + longer = self + else + shorter = self + longer = ary + end + idx = 0 + len = shorter.size + while idx < len + hash[shorter[idx]] = true + idx += 1 + end + idx = 0 + len = size + while idx < len + v = longer[idx] + if hash[v] + return true + end + idx += 1 + end + false + end + ## # call-seq: # ary.flatten -> new_ary diff --git a/mrbgems/mruby-array-ext/test/array.rb b/mrbgems/mruby-array-ext/test/array.rb index 2955ef391..3f73ad8b9 100644 --- a/mrbgems/mruby-array-ext/test/array.rb +++ b/mrbgems/mruby-array-ext/test/array.rb @@ -119,6 +119,14 @@ assert("Array#intersection") do assert_equal [1, 8], a.intersection(b,c) end +assert("Array#intersect?") do + a = [ 1, 2, 3 ] + b = [ 3, 4, 5 ] + c = [ 5, 6, 7 ] + assert_true(a.intersect?(b)) + assert_false(a.intersect?(c)) +end + assert("Array#flatten") do assert_equal [1, 2, "3", {4=>5}, :'6'], [1, 2, "3", {4=>5}, :'6'].flatten assert_equal [1, 2, 3, 4, 5, 6], [1, 2, [3, 4, 5], 6].flatten -- cgit v1.2.3