RipperとRubyParser

今日とあるプルリク上でrubyで書かれたコードをパースする話が出てきました。

気になったので調べてみました。

 

Rubyで書かれたコードをパースする方法はいくつかあるようです。

 

RubyParserを使う

gem install ruby_parser を実行してruby_parserをローカルに入れます。

その後、以下のようにすればコードをパースできます。

irb(main):001:0> require 'ruby_parser'

=> true

irb(main):003:0> p RubyParser.new.parse 'hello world'

s(:call, nil, :hello, s(:call, nil, :world))

=> s(:call, nil, :hello, s(:call, nil, :world))

 

 

 

Riooerを使う

RubyにはRipperというライブラリが用意されているようです。

以下はRipperのリファレンスマニュアルリンクです。

docs.ruby-lang.org

 

以下のようにパースできます。

irb(main):004:0> p Ripper.sexp('hello world')

[:program, :command, [:@ident, "hello", [1, 0, [:args_add_block, :vcall, [:@ident, "world", [1, 6]], false]]]]

=> [:program, [[:command, [:@ident, "hello", [1, 0]], [:args_add_block, [[:vcall, [:@ident, "world", [1, 6]]]], false]]]]

 

 

感想その他

Ripperはgem installしなくても使えるので楽ですが、パースした結果はRubyParserの方がみやすいと感じました。