Ruby Weekly is a weekly newsletter covering the latest Ruby and Rails news.

Fun with Ruby’s Abstract Syntax Trees

By Peter Cooper / December 15, 2008

ast-img.pngWhenever you run a Ruby program, Ruby's parser processes the code and turns it into an "abstract syntax tree" (an AST) which can then be either turned into bytecode for YARV (on Ruby 1.9) or be interpreted immediately (as with Ruby 1.8).

While a programming language allows programmers to represent the logic of a program in a way that's both suitable for developers and computers to easily understand, abstract syntax trees act as a low-level tree representation of the program's mechanics. Given that ASTs are typically simple data structures, it's possible to use them to convert one language to another, to semantically analyze what a program is going to do, to detect repetition, or to optimize how the final program will run.

Ilya Grigorik has written Ruby AST for Fun and Profit, a fun blog post where he looks at interacting with Ruby ASTs. He links to some interesting libraries (including the excellent Parsetree), a talk by Marc Chung, and his own app, Ruby2Lolz, that can convert Ruby into LOLCODE (a scary and esoteric joke programming language that reads like COBOL on LSD).

Other Posts to Enjoy

Twitter Mentions