Created
April 1, 2009 18:53
-
-
Save citizen428/88836 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Enumerable | |
# operand can be a String or a Symbol | |
def filter(operand, value) | |
raise(ArgumentError, "Invalid operator") unless %w(> < >= <= ==).include?(operand.to_s) | |
return self if self.class == String | |
self.select { |el| el.send(operand, value) } | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# example use | |
# using a String as operand | |
test = [1,5,3,2,1,6,4,3,2,1] | |
test.filter('<', 5) # => [1, 3, 2, 1, 4, 3, 2, 1] | |
# using a Symbol as operand | |
quiz = [0,0,0,1,0,0,1,1,0,1] | |
attempted = quiz.filter(:==, 1) # => [1, 1, 1, 1] | |
# Passing and invalid argument | |
test.filter('lala', 0) # => | |
# ~> -:4:in `filter': Invalid operator (ArgumentError) | |
# ~> from -:19 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment