Skip to content
AgileLogics
4 min read

How Ruby Code Runs

Prerequisites: Your first Ruby program

When you run ruby hello.rb, the Ruby interpreter does the work in three steps:

  1. Parse — it reads your source code and checks that it's valid Ruby. A typo here is a syntax error, and nothing runs at all.
  2. Compile to bytecode — it turns the code into compact internal instructions for its virtual machine (called YARV). This happens automatically every time; you never see a compiled file.
  3. Execute — the virtual machine runs those instructions from the top of the file down.

Real-world analogy: a compiled language like C is a book translated in full before anyone reads it. Ruby is a live interpreter translating as the speaker talks — nothing to prepare in advance, at the cost of some speed.

Because code is only run when execution reaches it, some mistakes only appear at that moment:

puts "This line runs"
puts undefined_name
puts "This line never runs"
This line runs
hello.rb:2:in '<main>': undefined local variable or method 'undefined_name' for main (NameError)

puts undefined_name
     ^^^^^^^^^^^^^^

The first line printed before the error on line 2 stopped the program. The error message tells you the file, the line number, and what went wrong — always read it from left to right. The ^^^ marks underneath point at the exact part of the line that failed.

Ruby can also compile hot code to machine code while it runs, using its built-in YJIT compiler. That's a performance topic covered in Level 3; you don't need to think about it yet.