Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

String matcher #30

Closed
wants to merge 1 commit into from
Closed

String matcher #30

wants to merge 1 commit into from

Commits on Feb 10, 2022

  1. String matcher

    Most of the time when I'm using string scanner I am checking multiple patterns. In this case I usually have to join them in a single regex or I just check them with multiple elsif clauses. Instead, it would be nice to initialize a string scanner that could check multiple patterns and then return to me the value that I want. In this commit I introduce a `StringMatcher` object that does just that. For example:
    
    ```
    require "strmatch"
    
    NumberToken = Struct.new(:value, keyword_init: true)
    StringToken = Struct.new(:value, keyword_init: true)
    
    matcher = StringMatcher.new("12ab34")
    matcher.match(/\d+/) { |value| NumberToken.new(value: value.to_i) }
    matcher.match(/[a-z]+/) { |value| StringToken.new(value:) }
    
    until matcher.eos?
      case matcher.select
      in NumberToken[value:] if value >= 20
        puts "NUMBER: #{value.inspect} (big)"
      in NumberToken[value:] if value < 20
        puts "NUMBER: #{value.inspect} (small)"
      in StringToken[value:]
        puts "STRING: #{value.inspect}"
      end
    end
    ```
    
    Running the above example will produce:
    
    ```
    NUMBER: 12 (small)
    STRING: "ab"
    NUMBER: 34 (big)
    ```
    
    This is more ergonomic since you can now use pattern matching instead of a chain of if/elsif clauses.
    kddnewton committed Feb 10, 2022
    Configuration menu
    Copy the full SHA
    0a55c81 View commit details
    Browse the repository at this point in the history