Skip to content

Instantly share code, notes, and snippets.

@eric1234
Created September 21, 2009 17:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eric1234/190402 to your computer and use it in GitHub Desktop.
Save eric1234/190402 to your computer and use it in GitHub Desktop.
Using the match operator as an alternative to include?
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