This blog is part of our Ruby 2.6 series. Ruby 2.6.0 was released on Dec 25, 2018.

Ruby 2.6 added RubyVM::AST to generate the Abstract Syntax Tree of code. Please note, this feature is experimental and under active development.

As of now, RubyVM::AST supports two methods: parse and parse_file .

parse method takes a string as a parameter and returns the root node of the tree in the form of the object, RubyVM::AST::Node.

parse_file method takes the file name as a parameter and returns the root node of the tree in the form of the object, RubyVM::AST::Node.

Ruby 2.6.0-preview2

irb > RubyVM :: AST . parse ( "(1..100).select { |num| num % 5 == 0 }" ) => #<RubyVM::AST::Node(NODE_SCOPE(0) 1:0, 1:38): > irb > RubyVM :: AST . parse_file ( "/Users/amit/app.rb" ) => #<RubyVM::AST::Node(NODE_SCOPE(0) 1:0, 1:38): >

RubyVM::AST::Node has seven public instance methods - children , first_column , first_lineno , inspect , last_column , last_lineno and type .

Ruby 2.6.0-preview2

irb > ast_node = RubyVM :: AST . parse ( "(1..100).select { |num| num % 5 == 0 }" ) => #<RubyVM::AST::Node(NODE_SCOPE(0) 1:0, 1:38): > irb > ast_node . children => [ nil , #<RubyVM::AST::Node(NODE_ITER(9) 1:0, 1:38): >] irb > ast_node . first_column => 0 irb > ast_node . first_lineno => 1 irb > ast_node . inspect => "#<RubyVM::AST::Node(NODE_SCOPE(0) 1:0, 1:38): >" irb > ast_node . last_column => 38 irb > ast_node . last_lineno => 1 irb > ast_node . type => "NODE_SCOPE"

This module will majorly help in building a static code analyzer and formatter.