diff options
| author | Jun Hiroe <[email protected]> | 2014-04-24 22:49:52 +0900 |
|---|---|---|
| committer | Jun Hiroe <[email protected]> | 2014-04-24 23:04:46 +0900 |
| commit | d4bec4d6571132e759658bb8819d71d96b83d55c (patch) | |
| tree | d7af0f752ab92b33b36fd47e945421e940410d3a /mrbgems/mruby-array-ext | |
| parent | 39c036ab037b13d62149f4736ae7808e411d0029 (diff) | |
| download | mruby-d4bec4d6571132e759658bb8819d71d96b83d55c.tar.gz mruby-d4bec4d6571132e759658bb8819d71d96b83d55c.zip | |
Add Array#delete_if
Diffstat (limited to 'mrbgems/mruby-array-ext')
| -rw-r--r-- | mrbgems/mruby-array-ext/mrblib/array.rb | 32 | ||||
| -rw-r--r-- | mrbgems/mruby-array-ext/test/array.rb | 13 |
2 files changed, 45 insertions, 0 deletions
diff --git a/mrbgems/mruby-array-ext/mrblib/array.rb b/mrbgems/mruby-array-ext/mrblib/array.rb index 7da416cf8..bf9c09223 100644 --- a/mrbgems/mruby-array-ext/mrblib/array.rb +++ b/mrbgems/mruby-array-ext/mrblib/array.rb @@ -513,4 +513,36 @@ class Array self[idx, 0] = args self end + + ## + # call-seq: + # ary.delete_if { |item| block } -> ary + # ary.delete_if -> Enumerator + # + # Deletes every element of +self+ for which block evaluates to +true+. + # + # The array is changed instantly every time the block is called, not after + # the iteration is over. + # + # See also Array#reject! + # + # If no block is given, an Enumerator is returned instead. + # + # scores = [ 97, 42, 75 ] + # scores.delete_if {|score| score < 80 } #=> [97] + + def delete_if(&block) + return to_enum :delete_if unless block_given? + + idx = 0 + len = self.size + while idx < self.size do + if block.call(self[idx]) + self.delete_at(idx) + else + idx += 1 + end + end + self + end end diff --git a/mrbgems/mruby-array-ext/test/array.rb b/mrbgems/mruby-array-ext/test/array.rb index a82fb08b3..ba1d4fd75 100644 --- a/mrbgems/mruby-array-ext/test/array.rb +++ b/mrbgems/mruby-array-ext/test/array.rb @@ -223,3 +223,16 @@ assert("Array#insert") do b = ["a", "b", "c", "d"] assert_equal ["a", "b", "c", "d", nil, nil, 99], b.insert(6, 99) end + +assert("Array#delete_if") do + a = [1, 2, 3, 4, 5] + assert_equal [1, 2, 3, 4, 5], a.delete_if { false } + assert_equal [1, 2, 3, 4, 5], a + + a = [1, 2, 3, 4, 5] + assert_equal [], a.delete_if { true } + assert_equal [], a + + a = [ 1, 2, 3, 4, 5 ] + assert_equal [1, 2, 3], a.delete_if { |val| val > 3 } +end |
