LoginSignup
6
6

More than 5 years have passed since last update.

Array#delete_if の削除した要素を返すバージョンがほしい

Last updated at Posted at 2015-06-19

Array#delete_if でも self を返すのではなく、Array#delete のように削除した要素を返して欲しい。

module ArrayExtention
  def reject_if(&block)
    rejected = []

    delete_if do |value|
      rejected << value if block.call(value)
    end

    rejected
  end
end

array = *(1..5) #=> [1, 2, 3, 4, 5]
array.delete_if(&:odd?) #=> [2, 4]
array #=> [2, 4]

array = *(1..5) #=> [1, 2, 3, 4, 5]
array.extend(ArrayExtention)
array.reject_if(&:odd?) #=> [1, 3, 5]
array #=> [2, 4]

Array#delete_ifArray#delete の返り値の違いは
Ruby を始めた頃によく引っかかる事柄のひとつだと思うのですが、
なぜこのような違いがあるのでしょうね? わたし、きになります!

6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6