Skip to content

Instantly share code, notes, and snippets.

@quanon
Created June 18, 2015 08:50
Show Gist options
  • Save quanon/700d27931118e19d6e47 to your computer and use it in GitHub Desktop.
Save quanon/700d27931118e19d6e47 to your computer and use it in GitHub Desktop.
reject_if (delete_if の返り値を削除後の self ではなく、削除した要素に変更したバージョン)
module ArrayExtention
def reject_if(&block)
rejected = []
delete_if do |value|
if block.call(value) # or if yield
rejected << value
true # なくてもいいけど僕の好み的に明示的に true を返したかった。
end
end
rejected
end
end
array = [1, 2, 3, 4, 5]
array.delete_if(&:odd?) #=> [2, 4]
array #=> [2, 4]
array = [1, 2, 3, 4, 5]
array.extend(ArrayExtention)
array.reject_if(&:odd?) #=> [1, 3, 5]
array #=> [2, 4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment