This blog is part of our Ruby 2.6 series. Ruby 2.6.0-preview2 was recently released.

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

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

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

parse_file method takes file name as parameter and returns root node of the tree in the form of an object of 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 static code analyzer and formatter.