Practical examples of Ruby command-line interface examples for 2025
Fast-start examples of Ruby command-line interface examples
Let’s start where you actually live: the terminal. These first examples of Ruby command-line interface examples are small but realistic. You can save each snippet as a .rb file, mark it executable, and run it immediately.
chmod +x my_tool.rb
./my_tool.rb --help
Example of a single-file Ruby CLI with OptionParser
Ruby ships with OptionParser in the standard library, and it’s still one of the best examples of a built‑in CLI toolkit in any language.
#!/usr/bin/env ruby
## file: greet.rb
require 'optparse'
options = {
times: 1,
excited: false
}
parser = OptionParser.new do |opts|
opts.banner = "Usage: greet.rb [options] NAME"
opts.on("-t", "--times N", Integer, "Number of greetings") do |n|
options[:times] = n
end
opts.on("-e", "--excited", "Add an exclamation mark") do
options[:excited] = true
end
opts.on("-h", "--help", "Show this help") do
puts opts
exit
end
end
parser.parse!
name = ARGV.shift || "world"
suffix = options[:excited] ? "!" : "."
options[:times].times do
puts "Hello, #{name}#{suffix}"
end
Usage examples include:
./greet.rb Alice
./greet.rb --times 3 --excited Bob
This is a minimal but real example of a Ruby command-line interface example you might write to test a library, greet users in a demo, or scaffold more complex behavior.
Real examples of Ruby command-line interface examples used by developers
Before we build more tools, it helps to look at existing, real-world CLI programs written in Ruby. Some of the best examples include:
rails– the Rails application generator and task runnerbundle– the Bundler CLI for managing Ruby gemsjekyll– a static site generator popular with GitHub Pagesrubocop– a Ruby style and linting toolsass/scss– CSS preprocessor CLIs (historically Ruby-based)
These are not toy scripts; they’re widely used in production and are strong examples of Ruby command-line interface examples that ship with installers, man pages, and CI integrations. You can inspect their source on GitHub to see how mature Ruby CLIs are structured, tested, and packaged as gems.
A practical log analyzer: example of a Ruby CLI for operations teams
Operations folks constantly triage logs. Here’s a more realistic example of Ruby command-line interface examples: a log analyzer that counts HTTP status codes in a log file.
#!/usr/bin/env ruby
## file: log_stats.rb
require 'optparse'
options = {
min_status: 400,
top: 5
}
OptionParser.new do |opts|
opts.banner = "Usage: log_stats.rb [options] access.log"
opts.on("-m", "--min-status CODE", Integer, "Minimum status to count (default: 400)") do |code|
options[:min_status] = code
end
opts.on("-t", "--top N", Integer, "Show top N status codes (default: 5)") do |n|
options[:top] = n
end
end.parse!
file = ARGV.shift or abort "Missing log file. Try: log_stats.rb access.log"
counts = Hash.new(0)
File.foreach(file) do |line|
# # Assume common log format, status is the 9th field
parts = line.split
status = parts[8].to_i
next if status < options[:min_status]
counts[status] += 1
end
puts "Status code summary (>= #{options[:min_status]}):"
counts.sort_by { |_, c| -c }
.first(options[:top])
.each do |status, count|
puts "#{status}: #{count}"
end
Usage:
./log_stats.rb -m 500 -t 10 /var/log/nginx/access.log
This is the kind of example of a Ruby command-line interface example that tends to stick: small, targeted, and easy to customize for your own log format.
Building richer CLIs with Thor: some of the best examples
At some point, a single script with flags stops scaling. You want subcommands like mytool sync, mytool status, mytool config. Thor is a popular Ruby gem that provides that structure.
Install Thor:
gem install thor
Here’s one of the best examples of Ruby command-line interface examples using Thor: a simple project management helper with multiple subcommands.
#!/usr/bin/env ruby
## file: pm.rb
require 'thor'
class ProjectManager < Thor
desc "init NAME", "Create a new project directory"
def init(name)
Dir.mkdir(name) unless Dir.exist?(name)
File.write(File.join(name, 'README.md'), "# #{name}\n")
puts "Initialized project #{name}"
end
desc "todo [ITEM]", "Add or list TODO items"
def todo(item = nil)
file = 'TODO.txt'
File.write(file, "", mode: 'a') unless File.exist?(file)
if item
File.open(file, 'a') { |f| f.puts("- #{item}") }
puts "Added TODO: #{item}"
else
puts File.read(file)
end
end
desc "version", "Show version"
def version
puts "pm 0.1.0"
end
end
ProjectManager.start(ARGV)
Usage examples include:
./pm.rb init blog
./pm.rb todo "Write first post"
./pm.rb todo
./pm.rb version
This pattern—class-based commands, desc annotations, and a single start call—is a very common example of Ruby command-line interface examples in modern tooling. Many code generators and API clients follow this layout.
For more background on CLI design patterns (even if language-agnostic), the U.S. Digital Services Playbook offers thoughtful guidance on usability and developer experience in tools.
Examples of Ruby command-line interface examples for data and APIs
Ruby remains a solid choice for quick data pulls and API calls. In 2024–2025, that often means JSON APIs, CSV exports, and light ETL scripts.
API client: example of a Ruby CLI hitting a JSON endpoint
Here’s a trimmed-down CLI that fetches JSON from a public API and prints a table. You can adapt this pattern to internal services.
#!/usr/bin/env ruby
## file: weather_cli.rb
require 'optparse'
require 'net/http'
require 'json'
options = { limit: 3 }
OptionParser.new do |opts|
opts.banner = "Usage: weather_cli.rb [options] CITY"
opts.on("-l", "--limit N", Integer, "Limit number of forecast entries") do |n|
options[:limit] = n
end
end.parse!
city = ARGV.shift or abort "City name required"
## Example endpoint; replace with your own API
uri = URI("https://api.weather.gov/alerts/active?area=#{city[0,2].upcase}")
response = Net::HTTP.get_response(uri)
abort "HTTP error: #{response.code}" unless response.is_a?(Net::HTTPSuccess)
data = JSON.parse(response.body)
alerts = data.fetch('features', [])[0, options[:limit]]
puts "Active alerts near #{city} (source: weather.gov)"
alerts.each do |alert|
props = alert['properties']
puts "- #{props['event']}: #{props['headline']}"
end
The National Weather Service API is documented at weather.gov/documentation/services-web-api, a good example of how government APIs are structured. This script is one of those examples of Ruby command-line interface examples that ties directly into real-world data.
Testing and packaging: turning examples into real tools
Toy examples of Ruby command-line interface examples are fun, but the moment you want teammates to rely on your tool, you need a bit more structure.
Testing a Ruby CLI
RSpec is still the go‑to test framework. You can test CLIs by invoking them as subprocesses or by calling the underlying classes.
## spec/pm_spec.rb
require 'open3'
RSpec.describe 'pm CLI' do
it 'prints version' do
stdout, status = Open3.capture2("ruby pm.rb version")
expect(status.success?).to eq(true)
expect(stdout).to include("pm 0.1.0")
end
end
The Ruby documentation at ruby-lang.org includes guidance on testing and standard libraries that pair well with CLI tools.
Packaging as a gem with an executable
Most of the best examples of Ruby command-line interface examples you know (rails, bundle) are shipped as gems with executables declared in the gemspec:
## example.gemspec
spec.executables = ["mytool"]
spec.bindir = "exe"
Then you create exe/mytool as a tiny launcher:
#!/usr/bin/env ruby
require "mytool"
MyTool::CLI.start(ARGV)
This pattern lets users install your CLI with a single gem install mytool and run mytool directly from the shell.
2024–2025 trends shaping new Ruby CLI examples
Several trends are influencing how new examples of Ruby command-line interface examples are built today:
Developer experience first. Tools like rails, rubocop, and bundle have raised expectations for helpful error messages, rich --help output, and sensible defaults. Even tiny scripts now tend to include --help and --version flags.
JSON in, JSON out. With microservices and observability stacks, CLIs increasingly emit structured JSON for downstream tools like jq or log aggregators. Ruby’s JSON library and Oj gem make this straightforward.
Security awareness. Scripts that touch credentials, PHI, or sensitive operational data need to be careful. Even for command‑line tools, guidance from organizations like NIST on secure coding and configuration handling is worth reviewing when you build internal CLIs for healthcare, finance, or government work.
Cross-language workflows. Ruby CLIs often orchestrate tools written in other languages—calling Python for data science, or kubectl for Kubernetes. That orchestration role is one of the quieter but best examples of Ruby command-line interface examples in modern DevOps pipelines.
FAQ: common questions about Ruby CLI usage
What are some real examples of Ruby command-line interface examples in production?
Real examples include the rails generator and task runner, the bundle gem manager, jekyll for static sites, and rubocop for linting. All of these are Ruby CLIs used daily in professional environments.
Can I build cross-platform tools with these examples of Ruby command-line interface examples?
Yes. As long as Ruby runs on the target system (Linux, macOS, Windows via RubyInstaller or WSL), the same CLI script usually works with minimal adjustments. Be careful with file paths, encodings, and OS-specific shell behavior.
Is Thor the only way to structure bigger Ruby CLIs?
No. Thor is popular, but other gems like GLI and Commander offer similar abstractions. Some of the best examples of Ruby command-line interface examples use only OptionParser plus a small internal command router to reduce dependencies.
How do I distribute an internal Ruby CLI to my team?
Common approaches include packaging it as a gem, checking it into a shared repository with a bin/ script, or wrapping it in a Docker image. For larger organizations, publishing a private gem server or artifact repository makes versioning and updates easier.
Where can I learn more about designing usable command-line tools?
While not Ruby-specific, many universities and government agencies publish guidance on usable software interfaces. For example, usability research from institutions like Harvard or general software usability principles from NIST can inform how you design prompts, defaults, and error messages in your CLI tools.
These examples of Ruby command-line interface examples should give you enough patterns to build your own: simple scripts with OptionParser, multi-command tools with Thor, data and API helpers, and production-ready CLIs with tests and packaging. Start small, keep the interface predictable, and evolve your script the way the best Ruby tools have done for years.
Related Topics
Practical examples of examples of Ruby regular expressions examples
The best examples of Ruby looping constructs: 3 practical examples for real projects
Practical examples of Ruby command-line interface examples for 2025
The best examples of examples of basic Ruby syntax examples for beginners
Modern examples of Ruby web scraping examples - practical code snippets
Practical examples of Ruby exception handling examples for real apps
Explore More Ruby Code Snippets
Discover more examples and insights in this category.
View All Ruby Code Snippets