2015-10-17 41 views

回答

2

這將顯示YARV指令

code = <<END 
x=1 
x.to_s 
puts x 
END 
puts RubyVM::InstructionSequence.compile(code).disasm 

如果您想了解更多,你可以看看這本書紅寶石在顯微鏡下

這將是輸出

1.9.3-p547 :012 > code = <<END 
1.9.3-p547 :013"> x=1 
1.9.3-p547 :014"> x.to_s 
1.9.3-p547 :015"> puts x 
1.9.3-p547 :016"> END 
=> "x=1\nx.to_s\nputs x\n" 
1.9.3-p547 :017 > puts RubyVM::InstructionSequence.compile(code).disasm 
== disasm: <RubyVM::InstructionSequence:<compiled>@<compiled>>========== 
local table (size: 2, argc: 0 [opts: 0, rest: -1, post: 0, block: -1] s1) 
[ 2] x   
0000 trace   1            ( 1) 
0002 putobject  1 
0004 setlocal   x 
0006 trace   1            ( 2) 
0008 getlocal   x 
0010 send    :to_s, 0, nil, 0, <ic:0> 
0016 pop    
0017 trace   1            ( 3) 
0019 putself   
0020 getlocal   x 
0022 send    :puts, 1, nil, 8, <ic:1> 
0028 leave   
2

如果你使用了Rubinius你可以像這樣運行它,並獲得字節碼:

$ rbx compile simple.rb -o simple.bytecode 

你可以看到一個全面的解釋here和關於Rubinius的編譯here的解釋。

+0

即時通訊使用MRI,我想將MRI將我的示例代碼轉換爲字節或直接解釋它 –

+0

我不認爲MRI正在編譯爲字節碼。看到這個答案:http://stackoverflow.com/questions/717490/is-ruby-really-an-interpreted-language-if-all-of-its-implementations-are-compile – davidrac