How to Use bundle exec in Ruby: Simple Guide
Use
bundle exec before a Ruby command to run it with the gems specified in your Gemfile.lock. This ensures your script uses the exact gem versions your project depends on, avoiding conflicts.Syntax
The basic syntax of bundle exec is:
bundle exec <command> [arguments]
Here, bundle exec runs the given command using the gems listed in your project's Gemfile.lock. Any arguments are passed to the command.
bash
bundle exec ruby my_script.rb
Example
This example shows how to run a Ruby script using bundle exec to ensure it uses the correct gem versions.
ruby
# Gemfile source 'https://rubygems.org' gem 'colorize', '~> 0.8.1' # my_script.rb require 'colorize' puts 'Hello, world!'.colorize(:green)
Output
Hello, world! (in green text color)
Common Pitfalls
Common mistakes when using bundle exec include:
- Not running
bundle installfirst, so gems are missing. - Running commands without
bundle exec, causing the system to use wrong gem versions. - Using
bundle execwith commands not installed by Bundler.
Always run bundle install before using bundle exec and confirm your command is part of your bundle.
bash
Wrong way: ruby my_script.rb Right way: bundle exec ruby my_script.rb
Quick Reference
| Command | Description |
|---|---|
| bundle exec ruby my_script.rb | Run Ruby script with gems from Gemfile.lock |
| bundle exec rake db:migrate | Run rake task using bundled gems |
| bundle exec rspec | Run tests with correct gem versions |
Key Takeaways
Use
bundle exec to run commands with the exact gems your project needs.Always run
bundle install before using bundle exec to install gems.Without
bundle exec, your system might use wrong or global gem versions.Use
bundle exec with commands installed via your Gemfile for consistent results.