summaryrefslogtreecommitdiffhomepage
path: root/mrbgems
diff options
context:
space:
mode:
authorJun Hiroe <[email protected]>2014-04-21 13:28:56 +0900
committerJun Hiroe <[email protected]>2014-04-21 13:52:50 +0900
commitfcfab845602e25520e51f60ad33e4eb16dd58395 (patch)
tree9500ec081bb607778c2bb8b005128f9f3ee2ff3f /mrbgems
parente7f5cd7d4e21fe70aac62297c97e4ae70fad1e5f (diff)
downloadmruby-fcfab845602e25520e51f60ad33e4eb16dd58395.tar.gz
mruby-fcfab845602e25520e51f60ad33e4eb16dd58395.zip
Add Array#reject_bang
Diffstat (limited to 'mrbgems')
-rw-r--r--mrbgems/mruby-array-ext/mrblib/array.rb34
-rw-r--r--mrbgems/mruby-array-ext/test/array.rb14
2 files changed, 48 insertions, 0 deletions
diff --git a/mrbgems/mruby-array-ext/mrblib/array.rb b/mrbgems/mruby-array-ext/mrblib/array.rb
index 43d77b5f6..78d9ff78a 100644
--- a/mrbgems/mruby-array-ext/mrblib/array.rb
+++ b/mrbgems/mruby-array-ext/mrblib/array.rb
@@ -456,4 +456,38 @@ class Array
end
self
end
+
+ ##
+ # call-seq:
+ # ary.reject! { |item| block } -> ary or nil
+ # ary.reject! -> Enumerator
+ #
+ # Equivalent to Array#delete_if, deleting elements from +self+ for which the
+ # block evaluates to +true+, but returns +nil+ if no changes were made.
+ #
+ # The array is changed instantly every time the block is called, not after
+ # the iteration is over.
+ #
+ # See also Enumerable#reject and Array#delete_if.
+ #
+ # If no block is given, an Enumerator is returned instead.
+
+ def reject!(&block)
+ return to_enum :reject! unless block_given?
+
+ len = self.size
+ idx = 0
+ while idx < self.size do
+ if block.call(self[idx])
+ self.delete_at(idx)
+ else
+ idx += 1
+ end
+ end
+ if self.size == len
+ nil
+ else
+ self
+ end
+ end
end
diff --git a/mrbgems/mruby-array-ext/test/array.rb b/mrbgems/mruby-array-ext/test/array.rb
index 1fdfabe49..0b425281f 100644
--- a/mrbgems/mruby-array-ext/test/array.rb
+++ b/mrbgems/mruby-array-ext/test/array.rb
@@ -183,3 +183,17 @@ assert("Array#delete_if") do
assert_equal [1, 2, 3], a.delete_if { |i| i > 3 }
assert_equal [1, 2, 3], a
end
+
+assert("Array#reject!") do
+ a = [1, 2, 3, 4, 5]
+ assert_nil a.reject! { false }
+ assert_equal [1, 2, 3, 4, 5], a
+
+ a = [1, 2, 3, 4, 5]
+ assert_equal [], a.reject! { true }
+ assert_equal [], a
+
+ a = [1, 2, 3, 4, 5]
+ assert_equal [1, 2, 3], a.reject! { |val| val > 3 }
+ assert_equal [1, 2, 3], a
+end