Lesson 2 / 25

Installing Ruby, irb, Gems and Bundler

Install Ruby with a version manager and manage dependencies with Bundler.

Tools of the trade

Install Ruby with a version manager so each project can use the version it needs: rbenv, chruby with ruby-install, asdf or mise on macOS and Linux, and RubyInstaller on Windows. A .ruby-version file in a project records its version. irb (Interactive Ruby) is the REPL for experimenting, with syntax highlighting and autocompletion in recent versions. Libraries are packaged as gems and published on RubyGems.org. Bundler manages a project's dependencies: the Gemfile lists gems with version constraints (the pessimistic operator ~> 7.2 allows 7.x updates from 7.2 but not 8.0), bundle install resolves and installs them, Gemfile.lock pins exact versions (commit it for applications), and bundle exec runs commands with exactly those versions. bundle add <gem> adds a dependency. Use ri or the online documentation at ruby-doc.org for core classes. Editors such as VS Code with the Ruby LSP extension, or RubyMine, provide completion, navigation and debugging.

A project with Bundler

Gemfile declares dependencies; bundle exec uses the locked versions.

mise use ruby@3.4          # or: rbenv install 3.4.x && rbenv local 3.4.x
ruby -v

mkdir invoice_tool && cd invoice_tool
bundle init                 # creates a Gemfile
bundle add csv
bundle add rspec --group test

# Gemfile
# source "https://rubygems.org"
# ruby "~> 3.4"
# gem "csv"
# group :test do
#   gem "rspec", "~> 3.13"
# end

bundle install              # writes Gemfile.lock
bundle exec rspec           # run tools with the locked gem versions
irb                         # interactive experiments

A shopping list and a receipt

The Gemfile is your shopping list ("some rspec, version 3.something"); Gemfile.lock is the receipt with the exact versions bought. bundle exec makes sure you cook with what is on the receipt, not whatever happens to be in the cupboard.

Quick check: What does bundle exec do?

  • Installs Ruby
  • Publishes a gem
  • Formats code
  • Runs a command using exactly the gem versions recorded in Gemfile.lock
Answer

Runs a command using exactly the gem versions recorded in Gemfile.lock — bundle exec ensures the locked dependency versions are used.