Using Graphs to Build Your Own Ruby Pattern Matcher
There's More Than One Way To Skin a Rat!
- Start State
- Transitions to itself on any character (the asterisk)
- Also, transitions to the next standard state via a literal transition edge that matches on the letter "a"
- Transitions to itself on any character (the asterisk)
- Also, transitions to the next standard state via a literal transition edge that matches on the letter "a"
- Transitions to itself on any character (the asterisk)
- Also, transitions to the next standard state via a literal transition edge that matches on the letter "a"
- transitions to the terminal state via an always transition edge.
- First, create the root of the whole graph. This is ALWAYS a start state.
- Store that as the state we're currently adding transitions to. (line 9)
- Next, for each character in the test string we are matching against the string pattern create the appropriate transition.
- Add the newly created transition to the current state
- Set the current state to point to the destination of the new state provided by our new transition.
- Rinse, lather, repeat...
- Once that's done ALWAYS create a terminal state as the last state.
- Attach it to our current state by adding a transition always transition to the current state that points at the final state.
- First "compile" the test pattern provided by the user into a graph representation.
- Next make that graph the first state to be evaluated (a graph is really just represented by a start node that acts as the root.
- Next we read the next character from the test string provided by the user.
- We every transition of every state that has been queued for evaluation.
- For each transition that tests true on its can_do method grab that transition's destination state and place that into our next states list/array.
- Once we've done that for every state and transition until we've ran out of test string to process there should be at least one state in our next states queue that is ready to transition to the terminal state (assuming there is a match).
- If there is then return true! We have a winner!
- Else it's false and these strings don't match according to the given pattern.


Comments [2]