Ruby and the Interpreter Pattern


When we talk about compilers, we might hear terms such as “interpreters”, “translators” and even “patterns” but “Ruby”? Yes, as weird as it seems, we can talk about Ruby programming language when we talk about compilers. Why? Because there is a pattern called the “Interpreter pattern” which helps us to understand the behavior of programming languages, and one good implementation of this pattern can be seen using Ruby programming language.

Apart from understanding and interpreting the behavior of programming languages the interpreter pattern also adds functionality to the composite pattern, which is a pattern that represents a grammar.

By implementing the interpreter pattern, we can build S-Expressions that are similar to functional programming languages like LISP, Clojure and F#; and, in order to build these expressions, we need to use a framework called S-Expression Interpreter Framework (SIF), which is a domain-specific language that includes Ruby programming language.

What this framework does is, first: read a string that represents a source program; to do this, scan the input, we use the Ruby regular expression API. Then, a hand-written recursive parser does the syntactic analysis; this parser transforms the S-expressions into Ruby data values. Finally, an abstract syntax tree (AST) is created by traversing the Ruby data value that are, now, used as objects.

Ruby is a dynamic language and has many built-in features useful for lexical analysis like garbage collector, regular expressions, etc., that is why it was chosen to implement the S-Expression Interpreter Framework.

While reading about the S-Expression Interpreter Framework I noticed that this framework is really helpful to write and study interpreters. Also, I can confirm that, compared to other languages like Clojure, Ruby is a language that is easy to use and an example of this is that design patterns can be easily implemented with it and refactorings can be done fast and properly.

Comentarios