Commit fcfab845 authored by Jun Hiroe's avatar Jun Hiroe

Add Array#reject_bang

parent e7f5cd7d
...@@ -456,4 +456,38 @@ class Array ...@@ -456,4 +456,38 @@ class Array
end end
self self
end 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 end
...@@ -183,3 +183,17 @@ assert("Array#delete_if") do ...@@ -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.delete_if { |i| i > 3 }
assert_equal [1, 2, 3], a assert_equal [1, 2, 3], a
end 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
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment