Ruby : Compiling your source code to byte code

Hey, from ruby 2.3.0 its so easy to compile your source code to bytecodes the Ruby-VM understands.

byte_code = RubyVM::InstructionSequence.compile_file '/home/john/somefile.rb'

File.binwrite '/home/john/bytecode', byte_code.to_binary

and in Command Line

$ cat bytecode 

YARB�
IUsx86_64-linux*.*1

+1�!AA*1
!qy��������yyQ� E/home/john/somefile.rbE<main>E <class:A>EshivaEhelloEAEputsEcore#define_methodu����� 5M

 

The content of the file

class A
  def shiva
    puts 'hello'
  end
end

What is the purpose?

Well, ruby takes time to compile your source code into byte codes so you can load your bytecodes directly into ruby and execute. No overhead of grammar checking and compilation.

How to load?

instruction_from_byte_code = RubyVM::InstructionSequence.load_from_binary byte_code.to_binary

instruction_from_byte_code.eval
# => :shiva

Sources:

Aaron patterson’s talk : 2016 Rails conf Kansas

2 thoughts on “Ruby : Compiling your source code to byte code

  1. Orion says:

    How would i run the bytecode without irb.. Say a separate script.
    Cause
    byte_code = RubyVM::InstructionSequence.compile_file ‘/home/john/somefile.rb’

    then can’t be used to address
    instruction_from_byte_code = RubyVM::InstructionSequence.load_from_binary byte_code.to_binary

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s