summaryrefslogtreecommitdiffhomepage
path: root/mrbgems/mruby-array-ext
diff options
context:
space:
mode:
authorJun Hiroe <[email protected]>2014-04-27 23:31:58 +0900
committerJun Hiroe <[email protected]>2014-04-27 23:34:24 +0900
commitcdef46e3d99835c48592ab08d1383612786820a7 (patch)
tree9add21bf0010cbd8cf6848e98988088da4facec4 /mrbgems/mruby-array-ext
parentbbc237044d0fb1792dff8c5d2466f4e644821239 (diff)
downloadmruby-cdef46e3d99835c48592ab08d1383612786820a7.tar.gz
mruby-cdef46e3d99835c48592ab08d1383612786820a7.zip
Add Array#select_bang
Diffstat (limited to 'mrbgems/mruby-array-ext')
-rw-r--r--mrbgems/mruby-array-ext/mrblib/array.rb30
-rw-r--r--mrbgems/mruby-array-ext/test/array.rb14
2 files changed, 44 insertions, 0 deletions
diff --git a/mrbgems/mruby-array-ext/mrblib/array.rb b/mrbgems/mruby-array-ext/mrblib/array.rb
index 9ef7eb166..bddcd8ab8 100644
--- a/mrbgems/mruby-array-ext/mrblib/array.rb
+++ b/mrbgems/mruby-array-ext/mrblib/array.rb
@@ -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
diff --git a/mrbgems/mruby-array-ext/test/array.rb b/mrbgems/mruby-array-ext/test/array.rb
index c76423522..f94189356 100644
--- a/mrbgems/mruby-array-ext/test/array.rb
+++ b/mrbgems/mruby-array-ext/test/array.rb
@@ -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