summaryrefslogtreecommitdiffhomepage
path: root/mrbgems/mruby-array-ext/mrblib/array.rb
diff options
context:
space:
mode:
authorYukihiro "Matz" Matsumoto <[email protected]>2021-04-17 17:38:44 +0900
committerYukihiro "Matz" Matsumoto <[email protected]>2021-04-17 17:38:44 +0900
commit737254588b272ea898ebddd9fc4307fa555ddc35 (patch)
tree539505549d74f97586660e76b7300a47776e18f9 /mrbgems/mruby-array-ext/mrblib/array.rb
parent9d32d440ebf1ebd0684f5349316a15602bea5421 (diff)
downloadmruby-737254588b272ea898ebddd9fc4307fa555ddc35.tar.gz
mruby-737254588b272ea898ebddd9fc4307fa555ddc35.zip
array.rb: add `Array#intersect?` from Ruby3.0.1.
Diffstat (limited to 'mrbgems/mruby-array-ext/mrblib/array.rb')
-rw-r--r--mrbgems/mruby-array-ext/mrblib/array.rb41
1 files changed, 41 insertions, 0 deletions
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
@@ -193,6 +193,47 @@ class Array
##
# 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
# ary.flatten(level) -> new_ary
#