Search code examples
ruby-on-railsruby

how to run the bytecode generated by ruby?


I am new to the Ruby scripting language.

I was learning how to generate the byte code in Ruby. I found the answer for generating the byte code.

But I don't know how to run that generated byte code. I searched the internet, but I didn't get the answer for this.

Generating a byte code:-

puts RubyVM::InstructionSequence.compile("x = 50; x > 100 ? 'foo' : 'bar'").disassemble

The output is,

== 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        50
0004 setlocal         x
0006 trace            1
0008 getlocal         x
0010 putobject        100
0012 opt_gt           <ic:1>
0014 branchunless     20
0016 putstring        "foo"
0018 leave            
0019 pop              
0020 putstring        "bar"
0022 leave            

I don't know how to execute the same script, by using the generated byte code.

Anyone please explain me how to execute this.

Thanks in advance!


Solution

  • TL;DR; You are looking for .eval method.

    The .compile method would return an instance of RubyVM::InstructionSequence class, which has .eval method that evaluates/runs your "compiled" instructions.

    iseq = RubyVM::InstructionSequence.compile("x = 50; x > 100 ? 'foo' : 'bar'")    
    iseq.eval       # => "bar"
    

    Or, a oneliner:

    RubyVM::InstructionSequence.compile("x = 50; x > 100 ? 'foo' : 'bar'").eval