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 newGemfile.bundle install: Installs gems listed in theGemfile.bundle exec [command]: Runs a command using the gems from yourGemfile.
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
| Command | Description |
|---|---|
| bundle init | Create a new Gemfile in your project |
| bundle install | Install gems listed in the Gemfile |
| bundle update | Update gems to latest allowed versions |
| bundle exec [command] | Run a command using gems from the Gemfile |
| bundle list | Show 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.