mirror of
https://github.com/mruby/mruby
synced 2026-06-08 16:11:16 +00:00
Merge pull request #2139 from suzukaze/add-array.select_bang
Add Array#select_bang
This commit is contained in:
@@ -657,4 +657,34 @@ class Array
|
||||
end
|
||||
self
|
||||
end
|
||||
|
||||
##
|
||||
# call-seq:
|
||||
# ary.select! {|item| block } -> ary or nil
|
||||
# ary.select! -> Enumerator
|
||||
#
|
||||
# Invokes the given block passing in successive elements from +self+,
|
||||
# deleting elements for which the block returns a +false+ value.
|
||||
#
|
||||
# If changes were made, it will return +self+, otherwise it returns +nil+.
|
||||
#
|
||||
# See also Array#keep_if
|
||||
#
|
||||
# If no block is given, an Enumerator is returned instead.
|
||||
|
||||
def select!(&block)
|
||||
return to_enum :select! unless block_given?
|
||||
|
||||
idx = 0
|
||||
len = self.size
|
||||
while idx < self.size do
|
||||
if block.call(self[idx])
|
||||
idx += 1
|
||||
else
|
||||
self.delete_at(idx)
|
||||
end
|
||||
end
|
||||
return nil if self.size == len
|
||||
self
|
||||
end
|
||||
end
|
||||
|
||||
@@ -266,3 +266,17 @@ assert("Array#keep_if") do
|
||||
assert_equal [4, 5], a.keep_if { |val| val > 3 }
|
||||
assert_equal [4, 5], a
|
||||
end
|
||||
|
||||
assert("Array#select!") do
|
||||
a = [1, 2, 3, 4, 5]
|
||||
assert_nil a.select! { true }
|
||||
assert_equal [1, 2, 3, 4, 5], a
|
||||
|
||||
a = [1, 2, 3, 4, 5]
|
||||
assert_equal [], a.select! { false }
|
||||
assert_equal [], a
|
||||
|
||||
a = [1, 2, 3, 4, 5]
|
||||
assert_equal [4, 5], a.select! { |val| val > 3 }
|
||||
assert_equal [4, 5], a
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user