Technology and Software

Ruby 2.3.0 InstructionSequence

Ruby 2.3 has been released on Christmas day as every Ruby version. It comes with a nice present: the RubyVM::InstructionSequence class with methods to compile scripts, save them and load them later. A quick example:

rvm install ruby-2.3.0
rvm use ruby-2.3.0
cat > test.rb
class Christmas
  def self.day
    25
  end
end
p Christmas.day

cat > compile.rb
instruction_sequence = 
  RubyVM::InstructionSequence.compile_file("test.rb")
File.open("test.iseq", "wb") do |file|
  file.write(instruction_sequence.to_binary)
end

cat > instruction_sequence = nil
File.open("test.iseq", "rb") do |file|
  instruction_sequence =
    RubyVM::InstructionSequence.load_from_binary(file.read)
end
instruction_sequence.eval

ruby compile.rb
ls
compile.rb  execute.rb  test.iseq  test.rb
ruby execute.rb
25

It works!

InstructionSequence comes with a caveat:

The goal of this project is to provide “machine dependent” binary file to achieve:

  • fast bootstrap time for big applications
  • reduce memory consumption with several techniques

“Machine dependent” means you can’t migrate compiled binaries to other machines.

Does it means that the compiled code won’t work on another machine? I generated the .iseq file on a Ubuntu 12.04 machine and uploaded it to a Ubuntu 14.04 one, both 64 bit. It keeps working and the directory structure of the two machines can be different, despite the presence in the compiled code of metadata about the source file.

I invite the readers to check the other methods of the class. They let allow for the compilation of strings of text and procs, setting compilation options, disassembling iseq code plus several instance methods that operate on an instruction sequence.

Advertisements
Standard

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