解析Ruby

jieforest發表於2012-10-04
Suppose you need to parse a chunk of Ruby code (and by Ruby I obviously mean Ruby 1.9). What options do you have?

I want to rip it, rip it

The obvious choice is Ripper, an external interface to the Ruby’s parser which is distributed with the MRI Ruby itself. Let’s take a look…

CODE:

pry> require 'ripper'
=> true
pry> Ripper.sexp 'def hello(greet="world"); puts "hello #{greet}"; end'
=> [:program,
[[:def,
   [:@ident, "hello", [1, 4]],
   [:paren,
    [:params,
     nil,
     [[[:@ident, "greet", [1, 10]],
       [:string_literal,
        [:string_content, [:@tstring_content, "world", [1, 17]]]]]],
     nil,
     nil,
     nil]],
   [:bodystmt,
    [[:void_stmt],
     [:command,
      [:@ident, "puts", [1, 26]],
      [:args_add_block,
       [[:string_literal,
         [:string_content,
          [:@tstring_content, "hello ", [1, 32]],
          [:string_embexpr, [[:var_ref, [:@ident, "greet", [1, 40]]]]]]]],
       false]]],
    nil,
    nil,
    nil]]]]

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/301743/viewspace-745592/,如需轉載,請註明出處,否則將追究法律責任。