ruby 46 lines · 8 steps

Parsing CLI options with OptionParser

Ruby's standard OptionParser turns raw argv into a typed, validated options struct for a command-line tool.

Explained by highlit
1require 'optparse'
2require 'ostruct'
3 
4def parse_options(argv)
5 options = OpenStruct.new(
6 verbose: false,
7 format: :json,
8 workers: 1,
9 tags: []
10 )
11 
12 parser = OptionParser.new do |opts|
13 opts.banner = 'Usage: deploy [options] TARGET'
14 
15 opts.on('-v', '--[no-]verbose', 'Run with verbose output') do |v|
16 options.verbose = v
17 end
18 
19 opts.on('-f', '--format FORMAT', %i[json yaml text],
20 'Output format (json, yaml, text)') do |fmt|
21 options.format = fmt
22 end
23 
24 opts.on('-w', '--workers N', Integer, 'Number of parallel workers') do |n|
25 raise OptionParser::InvalidArgument, n.to_s unless n.positive?
26 options.workers = n
27 end
28 
29 opts.on('-t', '--tag TAG', 'Filter by tag (repeatable)') do |tag|
30 options.tags << tag
31 end
32 
33 opts.on('-c', '--config FILE', 'Path to config file') do |path|
34 options.config = File.expand_path(path)
35 end
36 
37 opts.on('-h', '--help', 'Show this message') do
38 puts opts
39 exit
40 end
41 end
42 
43 parser.parse!(argv)
44 options.target = argv.shift
45 options
46end
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Seeding a defaults object up front means every flag is optional and unset values still behave sensibly.
  2. 2OptionParser can coerce and validate arguments inline, rejecting bad input before your program logic runs.
  3. 3parse! mutates argv in place, leaving non-option arguments behind for you to consume as positionals.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Parsing CLI options with OptionParser — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code