A Gemfile lists all the libraries (called gems) your Ruby project needs. It helps keep your project organized and makes sure everyone uses the same versions.
0
0
Gemfile for project dependencies in Ruby
Introduction
When starting a new Ruby project and you want to add external libraries.
When sharing your project with others so they can install the same gems easily.
When you want to lock gem versions to avoid unexpected changes.
When deploying your Ruby app to a server and need to install dependencies automatically.
Syntax
Ruby
source 'https://rubygems.org' gem 'gem_name', 'version' # Example: gem 'rails', '~> 7.0.0'
The source line tells where to get gems from, usually RubyGems.org.
Each gem line adds a gem with an optional version.
Examples
Adds the latest version of the
nokogiri gem.Ruby
source 'https://rubygems.org' gem 'nokogiri'
Adds Rails version 7.0.x, allowing patch updates but not major upgrades.
Ruby
source 'https://rubygems.org' gem 'rails', '~> 7.0.0'
Adds
rspec gem with versions between 3.0 (inclusive) and 4.0 (exclusive).Ruby
source 'https://rubygems.org' gem 'rspec', '>= 3.0', '< 4.0'
Sample Program
This Gemfile adds the colorize gem to color text in the terminal. After running bundle install, you can use it in your Ruby code to print green text.
Ruby
source 'https://rubygems.org' gem 'colorize', '~> 0.8.1' # After creating this Gemfile, run: # bundle install # Then in your Ruby code: require 'colorize' puts 'Hello, world!'.colorize(:green)
OutputSuccess
Important Notes
Always run bundle install after changing the Gemfile to install new gems.
You can specify groups like group :development do ... end to load gems only in certain environments.
Keep your Gemfile.lock file in version control to lock gem versions for everyone.
Summary
A Gemfile lists all gems your Ruby project needs.
It helps manage gem versions and dependencies easily.
Run bundle install to install gems from the Gemfile.