9

Ripper is the the parsing library that ships with Ruby 1.9. It transforms Ruby code into an AST, like so:

pp Ripper.sexp("def foo; yield :a; return 1 end")

#=>

[:program,
 [[:def,
   [:@ident, "foo", [1, 4]],
   [:params, nil, nil, nil, nil, nil],
   [:bodystmt,
    [[:yield,
      [:args_add_block,
       [[:symbol_literal, [:symbol, [:@ident, "a", [1, 16]]]]],
       false]],
     [:return, [:args_add_block, [[:@int, "1", [1, 26]]], false]]],
    nil,
    nil,
    nil]]]]

Is there a library to take this AST and transform it back into Ruby code?

ruby_parser and ruby2ruby used to do this, but I would like to use Ripper as my parser. (Ruby 1.9 may even ship with such a library, but I'm struggling to find documentation even on Ripper itself)

skaffman
  • 398,947
  • 96
  • 818
  • 769
Jon Smock
  • 9,451
  • 10
  • 46
  • 49
  • I played around with https://github.com/svenfuchs/ripper2ruby given http://www.artweb-design.de/2009/7/5/ripper2ruby-modify-and-recompile-your-ruby-code, but it died with NoMethodError: undefined method `to_ruby' for #. Not sure where to go from there. – Seamus Abshere Feb 02 '11 at 20:35
  • I found that at some point, but it just didn't seem reliable. Thanks for offering up your experience with it. – Jon Smock Feb 02 '11 at 20:55

1 Answers1

6

See "Sorcerer". This works well but I found a bug when parsing methods. If you add src.emit("; ") below the line 301 of the file "lib/sorcerer/resource.rb", this will be fixed. But you may find more if you decide to use this. Good luck.

Guilherme Bernal
  • 8,183
  • 25
  • 43