Created
September 21, 2009 17:47
-
-
Save eric1234/190402 to your computer and use it in GitHub Desktop.
Using the match operator as an alternative to include?
This file contains 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
class Object | |
def =~ n | |
return n =~ self if n.is_a?(Enumerable) | |
false | |
end | |
end | |
module Enumerable | |
alias_method :=~, :include? | |
end | |
if __FILE__ == $0 | |
require 'test/unit' | |
class EnumMatchTest < Test::Unit::TestCase | |
def test_strings | |
assert('bar' =~ %w(foo bar baz)) | |
assert(%w(foo bar baz) =~ 'bar') | |
assert('boo' !~ %w(foo bar baz)) | |
assert(%w(foo bar baz) !~ 'boo') | |
end | |
def test_number | |
assert(10 =~ (1..20)) | |
assert((1..20) =~ 10) | |
assert(30 !~ (1..20)) | |
assert((1..20) !~ 30) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment