DEV Community

Seiei Miyagi for Okinawa Ruby User Group

Posted on

Using RubyVM::AbstractSyntaxTree.of in pry

Put following snippets to ~/.pryrc

unless defined?(SCRIPT_LINES__)
  SCRIPT_LINES__ = {}
end

Pry.config.hooks.add_hook(:before_eval, :"ast<3") do |code, _pry|
  SCRIPT_LINES__["(pry)"] = code.lines
  code
end

It works, yay!

% pry
[1] pry(main)> RubyVM::AbstractSyntaxTree.of(-> { puts :hi })
=> (SCOPE@1:32-1:45
 tbl: []
 args:
   (ARGS@1:32-1:32
    pre_num: 0
    pre_init: nil
    opt: nil
    first_post: nil
    post_num: 0
    post_init: nil
    rest: nil
    kw: nil
    kwrest: nil
    block: nil)
 body: (FCALL@1:35-1:43 :puts (ARRAY@1:40-1:43 (LIT@1:40-1:43 :hi) nil)))
[2] pry(main)>

I also wrote a irb version, including how RubyVM::AbstractSyntaxTree.of uses SCRIPT_LINES__.
https://dev.to/okinawarb/how-can-i-use-rubyvm-abstractsyntaxtree-in-irb-m2k

Enjoy AST!

Top comments (0)