Explain it simply
Explain it simply
A gem is a library packaged for sharing: a folder of Ruby files plus a name and a version number, such as rake 13.3.1. RubyGems is the system that downloads gems from rubygems.org and installs them on your computer, and the gem command is its front end. Bundler sits one level above: it manages the gems of one project, so everyone who works on that project runs the same versions.
Think of a Gemfile as a shopping list and Gemfile.lock as the receipt. The list says what you want, such as any rake that is compatible with version 13. The receipt records exactly what you got, down to the last digit, so the same shopping trip can be repeated on another computer.
Problem → Why → Solution
The problem: "it works on my machine"
Your script works today. Next month a teammate clones the project, runs it and sees a LoadError, because nobody wrote down which libraries it needs. Or the library author releases a new major version, your server installs the newest one and a method you depended on is gone. "It works on my machine" is the symptom of one problem: the exact versions of your dependencies live only in your head and on your computer.
A second, quieter trap is mixing up installing and loading. gem install puts files on disk, but your program only uses a library after require reads it.
# report.rb: only works on computers where this gem happens to be installed
require "colorize" # LoadError: cannot load such file -- colorize
puts "Report ready".greenWhy does this happen?
Nothing in the project says which gems it needs or which versions are acceptable. A Gemfile makes the need explicit, and the Gemfile.lock pins the answer, so installing becomes repeatable instead of a matter of luck.
Core concept: gems, versions and the lock file
| Term | What it is |
|---|---|
| gem | A packaged library with a name and a version |
| RubyGems | The system and the gem command that install gems |
| Bundler | Installs and loads exactly the gems one project needs |
| Gemfile | Your wish list of gems and acceptable versions |
| Gemfile.lock | The exact versions Bundler chose, dependencies of dependencies included |
| require | Loads an installed library into the running program |
Gem versions follow semantic versioning by convention: MAJOR.MINOR.PATCH, for example 3.1.4. A PATCH bump (3.1.4 to 3.1.5) should only fix bugs, a MINOR bump (3.1 to 3.2) should add features without breaking existing code, and a MAJOR bump (3 to 4) is allowed to break things. It is a promise by the author, not something Ruby enforces, so read the changelog before a major upgrade.
A version constraint tells Bundler which versions you accept. The operators are = (exactly), >= and <, and the most useful one, the pessimistic operator ~>, read as "compatible with". It lets the rightmost digit you wrote grow but never the digit before it. So ~> 1.4 means >= 1.4 and < 2.0, while ~> 1.4.2 means >= 1.4.2 and < 1.5. With ~> 1.4 you pick up new minor releases and patches; with ~> 1.4.2 only patches.
When you run bundle install, Bundler looks at every gem in the Gemfile, reads each gem's own dependencies, and searches for one set of versions that satisfies all the constraints. It writes the result to Gemfile.lock. From then on, bundle install on any machine installs exactly those versions, which is what makes builds repeatable. Run bundle update only when you want newer versions, and bundle exec when you want a command to see only the gems in the lock.
- Gemfile lists what the project wants
- bundle install resolves exact versions
- Gemfile.lock records the result
- bundle exec runs with only those gems
The Gemfile says what is acceptable; the Gemfile.lock records what you actually got.
General pattern
source "https://rubygems.org"
gem "name" # any version
gem "name", "~> MAJOR.MINOR" # compatible upgrades only
gem "name", ">= 1.2", "< 3.0" # an explicit range
group :development, :test do
gem "name" # only installed for these groups
endA Gemfile is plain Ruby. source says where to download from, and each gem line names a gem plus optional version constraints. A group block separates gems that only development or test needs.
Example: trying version constraints offline
Installing from a Gemfile needs a network, but understanding constraints does not. Ruby ships Gem::Version and Gem::Requirement, which compare versions by the same rules Bundler uses. The script below shows how comparing versions differs from comparing text, then prints a table testing six versions against both ~> 1.4 and ~> 1.4.2.
# Versions compare number by number, not letter by letter
puts "Text order: #{"1.10.0" > "1.9.9"}"
puts "Version order: #{Gem::Version.new("1.10.0") > Gem::Version.new("1.9.9")}"
puts "Pre-release: #{Gem::Version.new("2.0.0.pre1") < Gem::Version.new("2.0.0")}"
puts
# The same candidates tested against two constraints
candidates = %w[1.3.9 1.4.0 1.4.2 1.5.0 1.9.9 2.0.0]
compatible = Gem::Requirement.new("~> 1.4")
patch_only = Gem::Requirement.new("~> 1.4.2")
puts format("%-8s %-8s %s", "version", "~> 1.4", "~> 1.4.2")
candidates.each do |text|
version = Gem::Version.new(text)
ok_compatible = compatible.satisfied_by?(version)
ok_patch_only = patch_only.satisfied_by?(version)
puts format("%-8s %-8s %s", text, ok_compatible, ok_patch_only)
end
puts
# A dependency is a gem name plus a requirement
dependency = Gem::Dependency.new("rack", "~> 3.0")
puts dependency
puts dependency.match?("rack", "3.1.2")
puts dependency.match?("rack", "4.0.0")Code breakdown
- Text vs version order
Gem::Version.new("1.10.0") > Gem::Version.new("1.9.9")Gem::Version splits on "." and compares 1, 10, 0 with 1, 9, 9 as numbers, so the result is true. The plain string comparison "1.10.0" > "1.9.9" goes character by character, where "1" sorts before "9", so it is false.
- Pre-release
Gem::Version.new("2.0.0.pre1") < Gem::Version.new("2.0.0")A version containing letters (pre1, rc1, beta) counts as a pre-release and always sorts below the final release, so 2.0.0.pre1 comes before 2.0.0.
- Two requirements
patch_only = Gem::Requirement.new("~> 1.4.2")Gem::Requirement accepts the same constraint strings you write in a Gemfile. Building two of them, ~> 1.4 and ~> 1.4.2, lets the same set of versions be tested against both.
- The table
ok_compatible = compatible.satisfied_by?(version)satisfied_by? returns true or false for one version. ~> 1.4 accepts 1.5.0 and 1.9.9 while ~> 1.4.2 rejects them. Only 1.4.2 passes both, and 2.0.0 is rejected by both.
- Gem::Dependency
dependency = Gem::Dependency.new("rack", "~> 3.0")A gem line in a Gemfile is a name plus a requirement. match? checks both the name and the version, so rack 3.1.2 gives true and rack 4.0.0 gives false.
Text order: false
Version order: true
Pre-release: true
version ~> 1.4 ~> 1.4.2
1.3.9 false false
1.4.0 true false
1.4.2 true true
1.5.0 true false
1.9.9 true false
2.0.0 false false
rack (~> 3.0)
true
falseThe gem command
The gem command manages gems for the whole machine. install, search and update talk to rubygems.org and need a network, while list, info, dependency, which and env only look at what is already on this machine and work offline. gem dependency minitest shows what minitest itself needs, which makes "dependencies of dependencies" visible. gem which shows the file require would load, handy when you suspect the wrong version.
gem install rake # download and install the newest version (needs network)
gem install rake -v 13.0.6 # install one specific version
gem list # every installed gem and its versions
gem list rake # only gems whose name matches
gem info rake # summary of one gem
gem dependency minitest # what minitest itself depends on
gem which minitest # the file that require "minitest" would load
gem env # RubyGems version and install paths
gem uninstall rake # remove a gemGemfile and Gemfile.lock
The Gemfile below asks for two gems: rake with ~> 13.0, and minitest with ~> 6.0 inside a test group. The Gemfile.lock under it comes from a real run of bundle install --local with Bundler 4.0.20. The real file also has a CHECKSUMS section, left out here. The version numbers, PLATFORMS and the other sections will differ on your machine.
source "https://rubygems.org"
gem "rake", "~> 13.0"
group :test do
gem "minitest", "~> 6.0"
endGEM
remote: https://rubygems.org/
specs:
minitest (6.0.0)
prism (~> 1.5)
prism (1.8.2)
rake (13.3.1)
PLATFORMS
x64-mingw-ucrt
DEPENDENCIES
minitest (~> 6.0)
rake (~> 13.0)
BUNDLED WITH
4.0.20Notice that the Gemfile asks for two gems but the lock holds three. minitest needs prism, so Bundler picked and recorded it too. DEPENDENCIES is what you asked for, specs is what you really got. For an application, commit both Gemfile and Gemfile.lock to version control; if you write a library, follow your project's convention.
The daily Bundler workflow
1. bundle init
Creates an empty Gemfile with the source line in the project folder. It needs no network.
2. bundle add rake
Adds the gem line to the Gemfile and installs it at once. Editing the Gemfile by hand and running bundle install works too.
3. bundle install
If there is no lock file it resolves and writes one. If there is one it installs the locked versions. While the Gemfile is unchanged, the lock does not change.
4. bundle exec ruby app.rb
Runs the command with only the gems in Gemfile.lock. Requiring a gem that is not in the lock raises LoadError, so undeclared dependencies show up early.
5. bundle outdated and bundle update rake
outdated lists gems with newer releases, and update raises only the named gem as far as its constraint allows. Running bundle update with no name raises everything.
bundle init # create a Gemfile
bundle add rake # add a gem and install it
bundle install # install what the Gemfile / lock asks for
bundle exec ruby app.rb # run using only the locked gems
bundle outdated # which gems have newer releases (needs network)
bundle update rake # update one gem, within its constraint
bundle info rake # where a bundled gem livesWriting your own gem: the gemspec
A .gemspec file describes a gem: its name, version, the files it contains, the Ruby version it needs and its own dependencies. gem build price_tools.gemspec produces the price_tools-0.1.0.gem file; this exact gemspec was built that way without warnings. A library puts its dependencies in the gemspec with add_dependency, not in the Gemfile, and a single gemspec line in the Gemfile makes Bundler read them.
Gem::Specification.new do |spec|
spec.name = "price_tools"
spec.version = "0.1.0"
spec.summary = "Small helpers for working with prices"
spec.authors = ["Your Name"]
spec.license = "MIT"
spec.files = Dir["lib/**/*.rb"]
spec.require_paths = ["lib"]
spec.required_ruby_version = ">= 3.2"
spec.add_dependency "rack", "~> 3.0"
spec.add_development_dependency "minitest", "~> 6.0"
endIn real projects
Where this shows up in real projects
Almost every Ruby application has a Gemfile and a Gemfile.lock at its root, Rails apps included. CI and production servers run bundle install against the committed lock, so they get the versions you tested. When building a Docker image, it is common to copy Gemfile and Gemfile.lock first and run bundle install, so that changing source code does not reinstall every gem.
A typical routine is to check bundle outdated, raise gems one at a time with bundle update gemname, run the tests and commit the lock. Small, frequent upgrades are easier and safer than one giant jump after two years, because security fixes usually arrive in new versions. Tools such as Dependabot automate the routine by opening pull requests that change Gemfile.lock.
Common mistakes
Common mistakes
1. Installed on the machine but missing from the Gemfile
require "csv" works under plain ruby, but bundle exec ruby in a project whose Gemfile does not list csv raises LoadError, because bundle exec only sees the gems in Gemfile.lock. Ruby 4.0.9 also prints a warning suggesting you add csv to the Gemfile. The fix is to add gem "csv" to the Gemfile and run bundle install.
2. Reading ~> 1.4 as 1.4.x
~> 1.4 means >= 1.4 and < 2.0, so it accepts 1.9.9 too. Write ~> 1.4.2 when you want patches only. The table above shows 1.5.0 being decided differently by the two.
3. Running bundle update with no gem name
Running a bare bundle update to fix one thing raises every gem as far as the constraints allow, which can bring in many unexpected changes. Raise one gem at a time with bundle update gemname.
4. Not committing an application's Gemfile.lock
Without a lock, each machine can resolve different versions even under the same constraints, and the "works on my machine" problem returns. Commit Gemfile.lock for an application.
$ bundle exec ruby -e 'require "csv"'
cannot load such file -- csvBest practices
Best practices
- In an application, constrain every gem with ~> MAJOR.MINOR and commit Gemfile.lock.
- Run scripts with bundle exec so a gem missing from the Gemfile cannot be used by accident.
- Check bundle outdated regularly and upgrade one gem at a time in small steps; read the changelog before a MAJOR bump.
- Before adding a new gem, check whether it is maintained and when its last release was.
Mini challenge
Mini challenge: find the newest allowed version
Imitate a tiny piece of what Bundler does. Given a list of available versions and one or more constraint strings, write a method that finds the newest version satisfying all of them.
- newest_allowed(available, *requirements) returns a Gem::Version, or nil when nothing fits
- Skip pre-release versions such as 3.0.0.rc1
- Use Gem::Version and Gem::Requirement; do not compare versions as text
- Print the answer for "~> 2.1", "~> 2.1.0", ">= 2.0" with "< 3.0", ">= 2.0" alone and "~> 4.0", showing "none" for nil
AVAILABLE = %w[1.9.9 2.0.0 2.1.0 2.1.7 2.2.0 3.0.0.rc1 3.0.0].freeze
# TODO: return the newest version in `available` that satisfies every requirement
# string, ignoring pre-releases. Return nil when none fits.
def newest_allowed(available, *requirements)
end
# TODO: loop over five constraint lists and print one line per list, for example
# ~> 2.1 -> 2.2.0
# (use "none" when the method returns nil)Expected: Five lines are printed: ~> 2.1 -> 2.2.0 ~> 2.1.0 -> 2.1.7 >= 2.0, < 3.0 -> 2.2.0 >= 2.0 -> 3.0.0 ~> 4.0 -> none
Show hint
Gem::Requirement.new(*requirements) accepts several constraint strings at once. Then chain map to Gem::Version, reject(&:prerelease?), select and max.
Show solution
AVAILABLE = %w[1.9.9 2.0.0 2.1.0 2.1.7 2.2.0 3.0.0.rc1 3.0.0].freeze
def newest_allowed(available, *requirements)
requirement = Gem::Requirement.new(*requirements)
available.map { |text| Gem::Version.new(text) }
.reject(&:prerelease?)
.select { |version| requirement.satisfied_by?(version) }
.max
end
constraints = [["~> 2.1"], ["~> 2.1.0"], [">= 2.0", "< 3.0"], [">= 2.0"], ["~> 4.0"]]
constraints.each do |constraint|
answer = newest_allowed(AVAILABLE, *constraint)
puts "#{constraint.join(", ").ljust(14)} -> #{answer || "none"}"
endQuick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A gem is a named, versioned library; RubyGems installs for the whole machine and Bundler controls versions per project.
- In MAJOR.MINOR.PATCH, ~> lets only the rightmost digit grow, so ~> 1.4 means < 2.0 and ~> 1.4.2 means < 1.5.
- The Gemfile says what is acceptable and Gemfile.lock records what you got, so commit both for an application.
- bundle exec sees only the locked gems, and bundle update gemname raises one gem at a time.
Bundler — Getting started — Bundler