Is it possible to grab the AST of a block from Ruby itself?
I've had a look at both ParseTree and ruby_parser, but they both seem to have sketchy support (from what I've read) for Ruby 1.9.2. I need something that works well with 1.9.2.
Ripper is included in MRI 1.9 out of the box.
ruby-1.9.2-p180 :004 > require 'ripper'
=> true
ruby-1.9.2-p180 :005 > Ripper.sexp("def a; end")
=> [:program, [[:def, [:@ident, "a", [1, 4]], [:params, nil, nil, nil, nil, nil], [:bodystmt, [[:void_stmt]], nil, nil, nil]]]]
In 1.8, Ruby executes the code by traversing the AST, so it is possible to get the AST for a given method/block. In 1.9 it is not so; the code is first parsed, then converted to YARV bytecode, and then executed. Not the source, nor AST is kept after the translating step, and the latter is not reversible; hence you cannot get the AST for a block in 1.9.
来源:https://stackoverflow.com/questions/6894763/extract-the-ast-from-a-ruby-block