Our first program will demonstrate how to create command-line subcommands in Ruby. Here’s the full source code:
This Ruby script demonstrates how to create command-line subcommands using the OptionParser class. We define two subcommands, ‘foo’ and ‘bar’, each with its own set of options.
To run the program, save it as command_line_subcommands.rb and use ruby:
Now try the ‘bar’ subcommand:
But ‘bar’ won’t accept ‘foo’s flags:
This example demonstrates how to create a command-line tool with subcommands in Ruby. Each subcommand is implemented as a separate class with its own option parser, allowing for flexible and modular command-line interfaces.
Next, we’ll look at environment variables, another common way to parameterize programs.