A Ruby reject! that returns the rejected items

I often need to do a reject! and return the rejected items instead of the modified collection. This saves having to do a select beforehand.

An example of how accomplish this:

options = { :a => 1, :b => 2, :c => 3 }
rejects = Hash[*options.select { |k, v| k == :b && options.delete(k) }.flatten]

assert_equal { :a => 1, :c => 3 }, options
assert_equal { :b => 2 }, rejects

This could be written as a method of the Hash class and an alternative for Array.

For Hash, the code would look something like:

class Hash
  def extract!
    Hash[*self.select { |k, v| yield(k, v) && self.delete(k) }.flatten]
  end
end

options = { :a => 1, :b => 2, :c => 3 }
rejects = options.extract! { |k, v| k == :b }

assert_equal { :a => 1, :c => 3 }, options
assert_equal { :b => 2 }, rejects

If I am missing something obvious in Ruby that accomplishes the same, please leave a comment.

Published by

Jamie

Hi, I am the Managing Director of SonicIQ Limited in the UK. I have been working in the web development industry since 1999 and have been running SonicIQ since 2001. Currently Ruby On Rails is my preferred development platform. I am experienced in designing with web standards, HTML5, CSS3 and Javascript.

One thought on “A Ruby reject! that returns the rejected items”

  1. The array variation could look something like this

    class Array

    def extract!
    [].tap{|rejected| delete_if { |v| yield(v) && rejected << v }}
    end

    end

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>