# what: a Regexp-based parser. alainravet - 2016 jan SYNTAX_RULES = { /^PRINT\b/ => { /^PRINT\s*\z/ => :new_line_command, /^PRINT (.*)/ => :print_command, }, /HELP/i => :help_command, } def command_and_params_for(rules_subtree, text) captures = nil _, command_or_rules_subtree = rules_subtree.detect{|pattern, _command_or_rules_subtree| match = pattern.match(text) captures = match.captures if match } case command_or_rules_subtree when Symbol command = command_or_rules_subtree parameters = captures [command, parameters] when Hash rules_subtree = command_or_rules_subtree command_and_params_for(rules_subtree, text) end end # -- TEST -- TEST -- TEST -- TEST -- TEST -- TEST -- TEST -- TEST def assert_equal(expected, actual) unless expected == actual raise "\n*** ERROR: \n\texpected: #{expected.inspect}\n\tfound: #{actual.inspect}" end end assert_equal [:help_command, [] ], command_and_params_for(SYNTAX_RULES, 'HELP') assert_equal [:new_line_command, [] ], command_and_params_for(SYNTAX_RULES, 'PRINT') assert_equal [:print_command , ["hello world"]], command_and_params_for(SYNTAX_RULES, 'PRINT hello world') puts "SUCCESS"