本文簡要介紹ruby語言中 Ripper類
的用法。
Ripper
是一個 Ruby 腳本解析器。
您可以使用基於事件的樣式從解析器獲取信息。 Ruby 程序的抽象語法樹或簡單詞法分析等信息。
用法
Ripper
提供了一個簡單的接口,用於將程序解析為符號表達式樹(或 S-expression)。
理解解析器的輸出可能是一個挑戰,建議您使用 PP
來格式化輸出以便於閱讀。
require 'ripper' require 'pp' pp Ripper.sexp('def hello(world) "Hello, #{world}!"; end') #=> [:program, [[:def, [:@ident, "hello", [1, 4]], [:paren, [:params, [[:@ident, "world", [1, 10]]], nil, nil, nil, nil, nil, nil]], [:bodystmt, [[:string_literal, [:string_content, [:@tstring_content, "Hello, ", [1, 18]], [:string_embexpr, [[:var_ref, [:@ident, "world", [1, 27]]]]], [:@tstring_content, "!", [1, 33]]]]], nil, nil, nil]]]]
您可以在上麵的示例中看到,表達式以 :program
開頭。
從這裏開始,在 :def
的方法定義,後跟方法的標識符 :@ident
。在方法標識符之後是括號 :paren
和 :params
下的方法參數。
接下來是方法體,從:bodystmt
(stmt
含義語句)開始,其中包含方法的完整定義。
在我們的例子中,我們隻是返回一個 String
,所以接下來我們有 :string_literal
表達式。
在我們的 :string_literal
中,您會注意到兩個 @tstring_content
,這是 Hello,
和 !
的文字部分。在兩個 @tstring_content
語句之間是一個 :string_embexpr
,其中 embexpr
是一個嵌入式表達式。我們的表達式由一個局部變量或 var_ref
組成,其標識符 (@ident
) 為 world
。
資源
要求
-
ruby 1.9(僅支持 CVS HEAD)
-
bison 1.28 或更高版本(其他 yacc 不起作用)
相關用法
- Ruby Ripper.sexp用法及代碼示例
- Ruby Ripper.slice用法及代碼示例
- Ruby Ripper.tokenize用法及代碼示例
- Ruby Ripper.sexp_raw用法及代碼示例
- Ruby Ripper.lex用法及代碼示例
- Ruby RingServer類用法及代碼示例
- Ruby RingFinger類用法及代碼示例
- Ruby RingServer.new用法及代碼示例
- Ruby Range.end用法及代碼示例
- Ruby Regexp named_captures()用法及代碼示例
- Ruby Ractor.receive_if用法及代碼示例
- Ruby Range new()用法及代碼示例
- Ruby Rational.inspect用法及代碼示例
- Ruby Random.bytes用法及代碼示例
- Ruby Random hex()用法及代碼示例
- Ruby RFC2396_Parser.parse用法及代碼示例
- Ruby Range.size用法及代碼示例
- Ruby Rational.rational <=>用法及代碼示例
- Ruby Recorder類用法及代碼示例
- Ruby Ruby.parse_method_parameters用法及代碼示例
- Ruby RFC2396_Parser.new用法及代碼示例
- Ruby Regexp to_s()用法及代碼示例
- Ruby Regexp.eql?用法及代碼示例
- Ruby Row.delete用法及代碼示例
- Ruby Rational to_i()用法及代碼示例
注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 Ripper類。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。