This blog is part of our Ruby 2.6 series.
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 (Link is not available).
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
1irb> RubyVM::AST.parse("(1..100).select { |num| num % 5 == 0 }") 2=> #<RubyVM::AST::Node(NODE_SCOPE(0) 1:0, 1:38): > 3 4irb> RubyVM::AST.parse_file("/Users/amit/app.rb") 5=> #<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
1irb> ast_node = RubyVM::AST.parse("(1..100).select { |num| num % 5 == 0 }") 2=> #<RubyVM::AST::Node(NODE_SCOPE(0) 1:0, 1:38): > 3 4irb> ast_node.children 5=> [nil, #<RubyVM::AST::Node(NODE_ITER(9) 1:0, 1:38): >] 6 7irb> ast_node.first_column 8=> 0 9 10irb> ast_node.first_lineno 11=> 1 12 13irb> ast_node.inspect 14=> "#<RubyVM::AST::Node(NODE_SCOPE(0) 1:0, 1:38): >" 15 16irb> ast_node.last_column 17=> 38 18 19irb> ast_node.last_lineno 20=> 1 21 22irb> ast_node.type 23=> "NODE_SCOPE"
This module will majorly help in building a static code analyzer and formatter.