1

Is there any way to access the byte code created by the Ruby program for the following sample piece of code?

x=1
x.to_s
puts x
Drenmi
  • 8,492
  • 4
  • 42
  • 51

2 Answers2

2

If you're using Rubinius you can run it like this and get the bytecode:

$ rbx compile simple.rb -o simple.bytecode

You can see a comprehensive explanation here and an explanation about the Rubinius compilation here.

davidrac
  • 10,723
  • 3
  • 39
  • 71
  • Im using MRI and i want to will MRI convert my sample code to byte or directly interpret it – Subbi reddy dwarampudi Oct 17 '15 at 16:07
  • I don't think that MRI is compiling to bytecode. See this answer: http://stackoverflow.com/questions/717490/is-ruby-really-an-interpreted-language-if-all-of-its-implementations-are-compile – davidrac Oct 17 '15 at 17:27
2

This will display the YARV instructions

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

If you want to learn more about that you can look for the book Ruby under a Microscope

This would be the output

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          
sugaryourcoffee
  • 879
  • 8
  • 14