What it is
A command-line interface for running Ruby code, scripts, and managing gems.
Installation
Linux (Debian/Ubuntu)
sudo apt update
sudo apt install ruby-full
Linux (Fedora)
sudo dnf install ruby
macOS
Ruby is typically pre-installed. You can check with ruby --version. If you need a different version, use a version manager like rbenv or RVM.
Using rbenv (recommended):
# Install Homebrew if you don't have it
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
# Install rbenv
brew install rbenv ruby-build
# Add rbenv to your shell (add to ~/.zshrc or ~/.bash_profile)
echo 'eval "$(rbenv init - zsh)"' >> ~/.zshrc # or ~/.bash_profile
source ~/.zshrc # or source ~/.bash_profile
# Install a Ruby version
rbenv install 3.2.2 # Replace 3.2.2 with your desired version
# Set the global Ruby version
rbenv global 3.2.2
Windows
Download and install Ruby from the official RubyInstaller website: https://rubyinstaller.org/
Core Concepts
- Gems: Ruby packages that provide additional functionality. Managed by the
gemcommand. - IRB (Interactive Ruby): A command-line interactive shell for running Ruby code snippets.
- Bundler: A gem for managing application dependencies (gems). While not strictly part of the core
rubyCLI, it’s essential for most Ruby projects.
Commands / Usage
Running Ruby Code
-
Execute a script:
ruby my_script.rbRuns the Ruby code contained in
my_script.rb. -
Execute code from stdin:
echo "puts 'Hello, Ruby!'" | rubyPipes the string "puts 'Hello, Ruby!'" to the
rubyinterpreter, which executes it. -
Execute a single line of code:
ruby -e "puts 2 + 2"Executes the Ruby code provided as a string to the
-eflag. -
Run a script with arguments:
# my_script.rb puts "First arg: #{ARGV[0]}" puts "Second arg: #{ARGV[1]}" # Terminal ruby my_script.rb apple bananaPasses
appleandbananaas command-line arguments to the script, accessible via theARGVarray.
Interactive Ruby (IRB)
-
Start IRB:
irbOpens an interactive Ruby console where you can type and execute Ruby code line by line.
-
Start IRB with specific options (e.g., line editing):
irb -r readlineLoads the
readlinelibrary for better line editing capabilities in IRB.
Gem Management (gem command)
-
Install a gem:
gem install railsInstalls the specified gem and its dependencies.
-
Install a specific version of a gem:
gem install rails -v 7.0.4Installs version
7.0.4of therailsgem. -
List installed gems:
gem listShows all gems currently installed in the environment.
-
List gems matching a pattern:
gem list jsonLists all installed gems whose names contain "json".
-
Uninstall a gem:
gem uninstall railsRemoves the specified gem from your system.
-
Uninstall a specific version of a gem:
gem uninstall rails -v 7.0.4Removes only version
7.0.4of therailsgem. -
Update a gem:
gem update railsUpdates the
railsgem to the latest available version. -
Update all gems:
gem updateUpdates all installed gems to their latest available versions.
-
Search for gems:
gem search httpartySearches RubyGems.org for gems matching the query "httparty".
-
Show gem information:
gem info railsDisplays details about the
railsgem, including its version, homepage, and description. -
Specify gem source:
gem install cocoapods --source https://gems.cocoapods.org/Installs the
cocoapodsgem, explicitly usinghttps://gems.cocoapods.org/as the source.
Ruby Interpreter Options
-
Verbose output:
ruby -v my_script.rbPrints the Ruby version to standard error before running the script.
-
Enable warnings:
ruby -w my_script.rbTurns on warnings for potential style problems or dangerous constructs.
-
Enable even more warnings:
ruby -w -w my_script.rb # or ruby -Wall my_script.rbEnables even more verbose warnings.
-
Load a library:
ruby -r json -e "puts JSON.parse('[1, 2, 3]').inspect"Loads the
jsonlibrary before executing the code with-e. -
Specify include path:
ruby -I ./lib my_script.rbAdds the
./libdirectory to the list of paths Ruby searches for required files (require). -
Disable method cache:
ruby -F my_script.rbDisables the method cache, which can be useful for debugging.
-
Disable class cache:
ruby -f my_script.rbDisables the class cache, also for debugging purposes.
-
Set environment variable:
ruby -E UTF-8 my_script.rbSets the default external encoding to
UTF-8. Can also beUS-ASCII,ASCII-8BIT, etc. -
Set internal encoding:
ruby -I UTF-8 my_script.rbSets the default internal encoding to
UTF-8. -
Specify script encoding:
ruby -x my_script.rbTreats the script as having a magic comment (e.g.,
# encoding: utf-8) to determine its encoding. -
Debug mode:
ruby -d my_script.rbEnables debug output from the Ruby interpreter.
-
Profile script execution:
ruby -pg my_script.rbRuns the script and prints profiling information after execution.
-
Profile script execution (with line numbers):
ruby -pc my_script.rbRuns the script and prints profiling information with line numbers after execution.
-
Print to stderr:
ruby -s my_script.rb --flag --other=valueEnables script modification by command line flags. If
--flagis present, the global variable$flagwill be true. If--other=valueis present,$otherwill bevalue.
Common Patterns
-
Run a Ruby one-liner to process text:
echo "hello world" | ruby -ne 'puts $_.upcase'Reads input line by line (
-n), converts each line ($_) to uppercase, and prints it. -
Quickly test a Ruby snippet:
echo "puts Time.now" | rubyExecutes the
puts Time.nowcommand instantly. -
Install a specific gem version for a one-off task:
gem install json -v 2.6.1 ruby -r json -e 'puts JSON.generate({a: 1})'Installs a specific version of
json, then uses it in a one-liner. -
Use Bundler to run a script within a project’s gem context:
bundle exec ruby path/to/your/script.rbEnsures the script runs with the gems specified in the project’s
Gemfile.lock. -
Run IRB with a specific gem loaded:
irb -r some_gemStarts an IRB session with
some_gemalready required.
Gotchas
- Global vs. Local Gems: The
gem installcommand installs gems globally for the current Ruby version. For project-specific dependencies, Bundler (bundle install,bundle exec) is the standard and highly recommended approach. - Multiple Ruby Versions: If you have multiple Ruby versions installed (e.g., via
rbenvorRVM), ensure you are running therubyandgemcommands associated with the desired version.rbenvandRVMhelp manage this. requirepath: When usingrequire 'some_file', Ruby searches forsome_file.rb(or.so,.dll, etc.) in specific directories, including the current directory and paths specified byruby -I. It does not automatically search subdirectories unless explicitly configured.ARGVis an Array: Command-line arguments passed to a script are available in the globalARGVarray. Remember thatARGV[0]is the first argument,ARGV[1]is the second, and so on.- Encoding Issues: Be mindful of file and string encodings, especially when dealing with non-ASCII characters. Use magic comments (
# encoding: utf-8) orruby -Eflags if necessary.