Command Line Flags in Ruby
Here’s the translation of the Go code to Ruby, with explanations in Markdown format suitable for Hugo:
Our example program demonstrates how to use command-line flags in Ruby. Command-line flags are a common way to specify options for command-line programs. For example, in wc -l
the -l
is a command-line flag.
Ruby provides an optparse
library for parsing command-line options. We’ll use this library to implement our example command-line program.
require 'optparse'
# Define default values
options = {
word: 'foo',
numb: 42,
fork: false,
svar: 'bar'
}
# Parse command-line options
OptionParser.new do |opts|
opts.banner = "Usage: command_line_flags.rb [options]"
# Basic flag declarations are available for string, integer, and boolean options.
# Here we declare a string flag 'word' with a default value 'foo' and a short description.
opts.on("-w", "--word STRING", "a string") do |w|
options[:word] = w
end
# This declares 'numb' and 'fork' flags, using a similar approach to the 'word' flag.
opts.on("-n", "--numb INTEGER", Integer, "an int") do |n|
options[:numb] = n
end
opts.on("-f", "--fork", "a bool") do |f|
options[:fork] = f
end
# It's also possible to declare an option that uses an existing var declared elsewhere in the program.
opts.on("-s", "--svar STRING", "a string var") do |s|
options[:svar] = s
end
end.parse!
# Here we'll just dump out the parsed options and any trailing positional arguments.
puts "word: #{options[:word]}"
puts "numb: #{options[:numb]}"
puts "fork: #{options[:fork]}"
puts "svar: #{options[:svar]}"
puts "tail: #{ARGV}"
To experiment with the command-line flags program, save it as command_line_flags.rb
and run it with various options:
$ ruby command_line_flags.rb -w opt -n 7 -f -s flag
word: opt
numb: 7
fork: true
svar: flag
tail: []
Note that if you omit flags they automatically take their default values:
$ ruby command_line_flags.rb -w opt
word: opt
numb: 42
fork: false
svar: bar
tail: []
Trailing positional arguments can be provided after any flags:
$ ruby command_line_flags.rb -w opt a1 a2 a3
word: opt
numb: 42
fork: false
svar: bar
tail: ["a1", "a2", "a3"]
Use -h
or --help
flags to get automatically generated help text for the command-line program:
$ ruby command_line_flags.rb -h
Usage: command_line_flags.rb [options]
-w, --word STRING a string
-n, --numb INTEGER an int
-f, --fork a bool
-s, --svar STRING a string var
If you provide a flag that wasn’t specified to the OptionParser
, the program will print an error message:
$ ruby command_line_flags.rb -x
command_line_flags.rb: invalid option: -x
This example demonstrates how to use Ruby’s optparse
library to handle command-line flags, providing a flexible way to configure your Ruby programs from the command line.