0
0
RubyHow-ToBeginner · 3 min read

How to Use Bundler in Ruby: Simple Guide and Examples

Use bundler in Ruby by creating a Gemfile listing your gems, then run bundle install to install them. Use bundle exec to run commands with the gems specified in your Gemfile.
📐

Syntax

Bundler uses a Gemfile to list the gems your Ruby project needs. You write gem names and versions inside it. Then you run commands in the terminal to install and use these gems.

  • bundle init: Creates a new Gemfile.
  • bundle install: Installs gems listed in the Gemfile.
  • bundle exec [command]: Runs a command using the gems from your Gemfile.
ruby
source 'https://rubygems.org'
gem 'rails', '~> 7.0'
gem 'puma', '~> 5.0'
💻

Example

This example shows how to create a Gemfile, install gems, and run a Ruby script using Bundler.

ruby
# Step 1: Create a Gemfile
# Contents of Gemfile:
source 'https://rubygems.org'
gem 'colorize', '~> 0.8.1'

# Step 2: Run in terminal:
# bundle install

# Step 3: Create a Ruby script (example.rb):
require 'bundler/setup'
require 'colorize'

puts 'Hello, Bundler!'.colorize(:green)

# Step 4: Run the script with:
# bundle exec ruby example.rb
Output
Hello, Bundler! (in green text color)
⚠️

Common Pitfalls

Not running bundle install after changing the Gemfile: Your gems won't update or install until you do this.

Running Ruby scripts without bundle exec: This can cause version conflicts or missing gems because it uses system gems instead of your project gems.

Editing Gemfile.lock manually: Avoid this file; it is managed by Bundler to lock gem versions.

bash
# Wrong way (may cause errors):
ruby example.rb

# Right way:
bundle exec ruby example.rb
📊

Quick Reference

CommandDescription
bundle initCreate a new Gemfile in your project
bundle installInstall gems listed in the Gemfile
bundle updateUpdate gems to latest allowed versions
bundle exec [command]Run a command using gems from the Gemfile
bundle listShow installed gems for the project

Key Takeaways

Always list your gems in a Gemfile to manage dependencies cleanly.
Run bundle install after changing the Gemfile to install or update gems.
Use bundle exec to run Ruby commands with the correct gem versions.
Never edit Gemfile.lock manually; let Bundler handle it.
Bundler ensures your project uses consistent gem versions across environments.