Skip to content

Instantly share code, notes, and snippets.

@alainravet
Created January 15, 2016 14:03
Show Gist options
  • Select an option

  • Save alainravet/a7c2b0ba303e813871b6 to your computer and use it in GitHub Desktop.

Select an option

Save alainravet/a7c2b0ba303e813871b6 to your computer and use it in GitHub Desktop.

Revisions

  1. alainravet created this gist Jan 15, 2016.
    41 changes: 41 additions & 0 deletions regexp_parser.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@
    # 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"