Skip to content

Instantly share code, notes, and snippets.

@Veejay
Created March 15, 2012 22:09
Show Gist options
  • Save Veejay/2047303 to your computer and use it in GitHub Desktop.
Save Veejay/2047303 to your computer and use it in GitHub Desktop.
Adds an instance method to arrays that returns an array containing all the elements that satisfy a criterion defined by a block. The elements are REMOVED from the original array.
Array.class_eval do
def extract!
if block_given?
[].tap do |rejects|
delete_if do |element|
yield(element) and rejects << element
end
end
else
self
end
end
end
@Veejay
Copy link
Author

Veejay commented Mar 15, 2012

How useful is this method? Probably not very useful, it was mainly coded as an exercise. A use case scenario for such a method might be input sanitizing.

For example, you get an array as input and you want to make sure that all unwanted elements have been removed from the array before using it.

Using extract!, it's as simple as defining a series of filters (defined by blocks) and having array go through all of them successively. The "safe" array should come out in the end. The process of filtering in this case basically takes the form of a call to extract! using the blocks generated from criteria you defined (be it in the blocks themselves, in a personal format or using JSON/YAML/XML/YOU_NAME_IT).

At each step, it is of course possible to do something with the rejected elements (logging comes to mind for example).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment