From: Ruby Quiz Date: 2006-11-25T08:21:24+09:00 Subject: [QUIZ] DictionaryMatcher (#103) The three rules of Ruby Quiz: 1. Please do not post any solutions or spoiler discussion for this quiz until 48 hours have passed from the time on this message. 2. Support Ruby Quiz by submitting ideas as often as you can: http://www.rubyquiz.com/ 3. Enjoy! Suggestion: A [QUIZ] in the subject of emails about the problem helps everyone on Ruby Talk follow the discussion. Please reply to the original quiz message, if you can. -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= by Ken Bloom From time to time someone asks on ruby-talk how they can write a regexp of the form: /alligator|crocodile|bear|dinosaur|...|seven-thousandth-word/ It's not hard to write such a regexp, but Ruby has in internal limit on how big the regular expression can be, so users find they can't do this matching function easily. Implement a class DictionaryMatcher that determines whether any of the strings added to it are substrings of a string S. This should function as almost a drop-in replacement for a Regexp, therefore your implementation should support the following operations: # creates a new empty matcher dm=DictionaryMatcher.new # adds strings to the matcher dm << "string" dm << "Ruby" # determines whether a given word was one of those added to the matcher dm.include?("Ruby") # => true dm.include?("missing") # => false dm.include?("stringing you along") # => false # Regexp-like substing search dm =~ "long string" # => 5 dm =~ "rub you the wrong way" # => nil # will automatically work as a result of implementing # DictionaryMatcher#=~ (see String#=~) "long string" =~ dm # => true # implement the rest of the interface implemented by Regexps (well, almost) class DictionaryMatcher alias_method :===, :=~ alias_method :match, :=~ end If you can add additional features, like a case insensitivity option when creating a new DictionaryMatcher this is also very useful.