Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 134 ยท Getting Started

How Ruby Runs

See what happens when you run a Ruby file - parser, bytecode, the virtual machine, YJIT and ZJIT - plus how irb, gems, Bundler and version managers fit together.

Ruby is usually called an interpreted language, but that word hides a lot. When you run ruby script.rb, a real program (the interpreter) reads your text, turns it into a compact internal form, and executes that form on a virtual machine. Knowing this pipeline does not change how you write everyday code, yet it explains error messages, performance advice and a few surprises you will meet later. This lesson also covers the tools around the interpreter that every Ruby developer uses: the interactive shell irb, RubyGems, Bundler and version managers.

Some of those tools need your own computer (they install software or open a terminal), so those parts are shown as read-only snippets. Everything about the interpreter itself can be inspected live from inside a script, and you will do that here.

Which Ruby is this?

When people say "Ruby" they usually mean CRuby, the reference implementation written in C, also called MRI (Matz's Ruby Interpreter). Others exist, such as JRuby (on the Java virtual machine) and TruffleRuby (on GraalVM), but this course always means CRuby. A script can ask which interpreter runs it:

Ruby Asking the interpreter about itself

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

These constants are defined in every Ruby program. RUBY_VERSION is a string such as "4.0.9". Never compare versions as plain strings ("4.0.9" > "10.0" is wrong); Gem::Version compares each dotted part as a number. Version checks are the usual way for a library to support several Rubies.

From text to results: the pipeline

Every run goes through the same stages:

  1. Lexing and parsing. The text is split into tokens and arranged into a tree that follows Ruby's grammar. Since Ruby 3.4 the default parser is Prism, a hand-written parser that recovers from errors well, which is why syntax errors now show your code with ^~~ markers (see Your First Ruby Program). Prism is also available to your own programs and is what tools like editors and linters use.
  2. Compiling. The tree becomes YARV bytecode, a list of small instructions for Ruby's virtual machine (YARV stands for Yet Another Ruby VM).
  3. Executing. The virtual machine runs the instructions one by one with a stack. Memory for objects is managed automatically by the garbage collector.

You can look at the second stage directly. The next example compiles two lines and prints the instructions.

Ruby Looking at bytecode

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

You do not need to understand every line, but you can read the story. putobject_INT2FIX_1_ pushes the number 1 on the stack, putobject 2 pushes 2, opt_plus adds them (an optimized instruction for +), setlocal_WC_0 a@0 stores the result in the local variable a, then getlocal and opt_send_without_block ... mid:puts read a and call puts. The exact opcode names can change between versions; the point is that Ruby code becomes a short, predictable list of steps.

The local table at the top shows another useful fact: Ruby finds your local variables when it compiles the file, before any line runs. That is why a variable that is assigned later is already known (as nil) in a branch that never ran, a subtle behavior covered in Variables and Constants.

Loading code: require and the load path

A real program is split across many files. require "name" finds a file in the load path (a list of directories stored in $LOAD_PATH) and runs it once. require_relative "name" looks next to the current file instead. Libraries that ship with Ruby, such as json or set, are found through the same mechanism.

Our sandbox gives each run a throwaway directory, so we can create a file and load it:

Ruby Writing a file and requiring it

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

require returns true the first time and false afterwards, so loading the same file from many places is safe and cheap. In a script of your own on disk you would write require_relative "greeter" with no directory handling.

The backslash in \#{name} stops the heredoc of the outer script from interpolating; the text written to the file contains a normal #{name}. Heredocs are explained in Strings.

Default gems, bundled gems and the rest

Ruby's standard library is not one block. Some libraries are default gems: they ship with Ruby and load with a plain require. Others are bundled gems: they are installed along with Ruby, but in a project that uses Bundler you must list them in your Gemfile. Over the last releases several libraries moved from default to bundled (for example csv, base64, bigdecimal, observer and ostruct in Ruby 3.4 and 4.0), and a few were removed. The practical rule: if require "something" fails with a LoadError, add the gem to your Gemfile or install it with gem install. Let's see what is available here.

Ruby Which libraries load here

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

rack and nokogiri fail because this server has no third-party gems and no network to install them. The rescue clause works directly inside the block, a form you will learn in Exceptions. On your own computer you would add those gems with Bundler.

YJIT and ZJIT: making Ruby faster

The virtual machine alone is already reasonably quick, but Ruby can go further with a just-in-time (JIT) compiler. A JIT watches the program run, notices which methods are called often ("hot" code) and translates them into machine code for your processor.

  • YJIT (written in Rust, introduced in Ruby 3.1, production-ready for years) speeds up typical Rails-style applications noticeably. You switch it on with the command-line flag --yjit, the environment variable RUBY_YJIT_ENABLE=1, or at run time with RubyVM::YJIT.enable.
  • ZJIT is a newer compiler, also written in Rust, that arrived as an experimental option in Ruby 4.0. It works on a method at a time with a different internal design and is meant to become the long-term successor.
  • Which should you use? For production on Ruby 4.0, YJIT is the proven choice. ZJIT is something to watch.

A JIT is only available when the interpreter was built with it. A script can check safely:

Ruby Is a JIT present

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

On our server the answer is "built without", because the runner's Ruby is compiled from source with only the essentials. On a standard installation (Ruby from a version manager or a Docker image, for example) YJIT is normally present, but you still enable it explicitly. A JIT never changes what your program prints, only how quickly it gets there. The lesson Performance Tips shows where the real wins are, which are almost always better algorithms rather than flags.

Do not benchmark tiny scripts to judge a JIT. It needs time to warm up, so a program that runs for a fraction of a second never benefits.

The interactive shell: irb

On your computer you will use irb (Interactive Ruby) constantly. It reads one expression at a time, evaluates it and prints the result. It is the quickest way to try an idea, test a method or explore an unfamiliar object. This is a read-only example of a session:

TEXT
$ irb
irb(main):001> 6 * 7
=> 42
irb(main):002> name = "ruby"
=> "ruby"
irb(main):003> name.upcase
=> "RUBY"
irb(main):004> name.nope
(irb):4:in '<main>': undefined method 'nope' for an instance of String (NoMethodError)
irb(main):005> exit

After each line irb shows => and the value of the expression, which is why you never need puts to see a result there. Every Ruby expression has a value; that idea comes back in Conditionals. Useful irb commands are help, ls obj (list an object's methods), show_source and exit. Newer versions also offer syntax highlighting and multi-line editing.

Notice the wording of the error: undefined method 'nope' for an instance of String. For nil the message says for nil, as you saw earlier. Ruby 3.4 and later always use that "an instance of ..." phrasing.

Gems, Bundler and Gemfile

A gem is a packaged Ruby library with a name and a version, hosted at rubygems.org. The gem command installs them. Bundler goes a step further: it records exactly which gems and versions your project needs so that every computer, and your production server, runs identical code.

Ruby
# read-only example: Gemfile (a file in your project folder)
source "https://rubygems.org"

ruby "4.0.9"

gem "sinatra", "~> 4.0"
gem "csv"          # a bundled gem must be listed explicitly

group :development, :test do
  gem "minitest"
end
Terminal
# read-only example: the everyday commands
gem install colorize        # install one gem globally
bundle install              # install everything in the Gemfile and write Gemfile.lock
bundle exec ruby app.rb     # run with exactly the locked versions

Gemfile says what you want (the ~> 4.0 means "4.0 or newer, but below 5"), and Gemfile.lock records what you got. Commit both files. The details are in RubyGems and Bundler.

Installing Ruby step by step

The browser examples in this course need nothing installed, but sooner or later you will want Ruby on your own machine. The goal is the same everywhere: a recent Ruby (4.0 or later for this course), a terminal where ruby -v works, and an editor that understands Ruby.

Windows. The simplest route is RubyInstaller (rubyinstaller.org). Download the installer marked "with Devkit", run it, and keep the final option checked that runs ridk install; in the black window that opens, press Enter to accept the default components. The Devkit supplies the C compiler that gems with native extensions need. Open a new terminal (PowerShell or Windows Terminal) afterwards. If you plan to work with Rails or Linux-first tools, the alternative is WSL 2 with Ubuntu, where you follow the Linux steps below.

macOS. The Ruby that ships with macOS is old and meant for the system's own scripts, so do not use it for your work. Install the Xcode command line tools (xcode-select --install), then Homebrew, and then either brew install ruby or, better, a version manager such as mise or rbenv.

Linux. sudo apt install ruby-full (or your distribution's equivalent) works, but the packaged version is often behind. Install the build dependencies for your distribution (a compiler, make, and the development headers for OpenSSL, libyaml, zlib and libffi) and use a version manager, which compiles the Ruby you ask for.

Terminal
# read-only example: rbenv with ruby-build (macOS with Homebrew shown)
brew install rbenv ruby-build
rbenv init                      # follow the printed line to add to your shell profile
rbenv install 4.0.9             # downloads and compiles; takes a few minutes
rbenv global 4.0.9              # use it everywhere
# in a project folder, pin the version instead:
rbenv local 4.0.9               # writes a .ruby-version file

Another popular pair is ruby-install to compile Ruby and chruby to switch between versions. Whichever tool you choose, verify the result in a new terminal window, because old windows do not see changed settings:

Terminal
ruby -v        # ruby 4.0.x ...
gem -v         # RubyGems, installed with Ruby
irb            # the interactive shell; type exit to leave

If ruby -v prints an old version, another Ruby comes first in your PATH. which ruby (or where ruby on Windows) shows which one runs.

Running a script file

Saving code in a file and running it with the ruby command is how nearly every real program starts. The options you will use most are ruby file.rb (run a file, with extra words after the name passed to ARGV), ruby -e 'code' (run one line), ruby -c file.rb (check the syntax without running) and ruby -v (print the version). The demonstration below writes a script and starts the interpreter from inside Ruby with backticks, which is exactly what you would type in a terminal:

Ruby Writing and running a script file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The first two lines print Hello, world! (Ruby 4.0.9) and Hello, Ruby! (Ruby 4.0.9): the extra word after the file name arrived in ARGV. The -e line prints 42, and -c prints Syntax OK for the good file and a syntax error with a non-zero exit status for the bad one.

On Linux and macOS you can also make a script directly executable. Put #!/usr/bin/env ruby on the first line, run chmod +x hello.rb once, and start it with ./hello.rb. The env form finds whichever Ruby your PATH selects, which keeps it working with version managers.

Setting up your editor

Any text editor works, since a Ruby file is plain text, but a good setup catches mistakes while you type.

  • Visual Studio Code with the Ruby LSP extension is the most common free choice. It offers completion, go-to-definition, inline documentation, formatting and RuboCop diagnostics, and it installs the language server for you.
  • RubyMine (JetBrains) is a full IDE with a debugger, refactoring tools and built-in Rails support.
  • Vim, Neovim, Emacs and Zed can use the same language server, ruby-lsp, through their own plugin systems.

Whatever you pick, three habits pay off early: turn on format on save (so indentation is two spaces without thinking), install RuboCop to learn the community style (RuboCop and style), and keep a .ruby-version file in each project so your editor, terminal and teammates agree on the version. For larger projects, bundle init creates a Gemfile for dependencies (RubyGems and Bundler).

Managing Ruby versions

Operating systems often come with an old Ruby that they use for their own tools, so developers install their own with a version manager. It keeps several Rubies side by side and picks one per project from a .ruby-version file.

Terminal
# read-only example: installing and choosing Ruby with a version manager (mise shown)
mise use --global ruby@4.0
ruby -v
echo "4.0.9" > .ruby-version

Popular choices are mise, rbenv with ruby-build, asdf, chruby with ruby-install, and RVM. On Windows, RubyInstaller is the simplest route. Docker images such as ruby:4.0 are common for deployment. Which tool you use matters much less than using one and committing the version file, so that "works on my machine" also means "works on the server".

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the Ruby interpreter do with your source file before running it?

    CRuby parses the file (with Prism), compiles it to YARV bytecode and then executes the bytecode. A JIT can later compile hot methods to machine code.
  2. 2. require "json" is called twice in a program. What happens the second time?

    require remembers what it has loaded. The first call returns true, later calls return false and skip the file.
  3. 3. Why should you compare Ruby versions with Gem::Version instead of strings?

    As strings, "10.0" is smaller than "4.0" because "1" comes before "4". Gem::Version compares each dotted part numerically.
  4. 4. What is the difference between Gemfile and Gemfile.lock?

    You edit the Gemfile; bundle install resolves it and writes the exact versions to Gemfile.lock, which makes installs repeatable.
  5. 5. What does YJIT do?

    YJIT is a just-in-time compiler. It speeds up execution without changing what the program does.

Summary

  • ruby file.rb parses the file with Prism, compiles it to YARV bytecode and runs it on the virtual machine; a syntax error stops everything before any line executes.
  • RUBY_VERSION, RUBY_ENGINE and friends describe the running interpreter; compare versions with Gem::Version.
  • require loads a file once (returns true, then false); require_relative loads relative to the current file; $LOAD_PATH lists where Ruby looks.
  • Some standard libraries are now bundled gems: add them to your Gemfile when require raises LoadError.
  • YJIT (and the experimental ZJIT) compile hot code to machine code; they change speed, not behavior, and need to be enabled and available in your build.
  • irb is the interactive shell; Bundler and the Gemfile make installs repeatable; version managers keep several Rubies per machine.

Next: Variables and Constants