summaryrefslogtreecommitdiffhomepage
path: root/mrbgems/mruby-array-ext
diff options
context:
space:
mode:
authorYukihiro "Matz" Matsumoto <[email protected]>2019-09-16 07:52:19 +0900
committerYukihiro "Matz" Matsumoto <[email protected]>2019-09-16 10:10:09 +0900
commitf4117d81d2fef1276836c1f6e13ceba7d83c9d7b (patch)
tree9796832d43d830bf39b218845efbcc098b287f04 /mrbgems/mruby-array-ext
parent3daa53ce6335e265e3579534fa199ef458047865 (diff)
downloadmruby-f4117d81d2fef1276836c1f6e13ceba7d83c9d7b.tar.gz
mruby-f4117d81d2fef1276836c1f6e13ceba7d83c9d7b.zip
Add `Array#difference` method from Ruby2.6.
Diffstat (limited to 'mrbgems/mruby-array-ext')
-rw-r--r--mrbgems/mruby-array-ext/mrblib/array.rb16
-rw-r--r--mrbgems/mruby-array-ext/test/array.rb8
2 files changed, 24 insertions, 0 deletions
diff --git a/mrbgems/mruby-array-ext/mrblib/array.rb b/mrbgems/mruby-array-ext/mrblib/array.rb
index fc5d87f2c..f9f232321 100644
--- a/mrbgems/mruby-array-ext/mrblib/array.rb
+++ b/mrbgems/mruby-array-ext/mrblib/array.rb
@@ -126,6 +126,22 @@ class Array
##
# call-seq:
+ # ary.difference(other_ary1, other_ary2, ...) -> new_ary
+ #
+ # Returns a new array that is a copy of the original array, removing all
+ # occurences of any item that also appear in +other_ary+. The order is
+ # preserved from the original array.
+ #
+ def difference(*args)
+ ary = self.dup
+ args.each do |x|
+ ary = self - x
+ end
+ ary
+ end
+
+ ##
+ # call-seq:
# ary & other_ary -> new_ary
#
# Set Intersection---Returns a new array
diff --git a/mrbgems/mruby-array-ext/test/array.rb b/mrbgems/mruby-array-ext/test/array.rb
index a4e328b71..029325aab 100644
--- a/mrbgems/mruby-array-ext/test/array.rb
+++ b/mrbgems/mruby-array-ext/test/array.rb
@@ -93,6 +93,14 @@ assert("Array#union") do
assert_equal [1, 2, 3, 4, 5], a.union(b,c)
end
+assert("Array#difference") do
+ a = [1, 2, 3, 1]
+ b = [1, 4]
+ c = [1, 5]
+
+ assert_equal [2, 3], a.difference(b,c)
+end
+
assert("Array#&") do
a = [1, 2, 3, 1]
b = [1, 4]