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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Seeding a defaults object up front means every flag is optional and unset values still behave sensibly.
- 2OptionParser can coerce and validate arguments inline, rejecting bad input before your program logic runs.
- 3parse! mutates argv in place, leaving non-option arguments behind for you to consume as positionals.
Related explainers
python
import argparse import sys from pathlib import Path
Building a subcommand CLI with argparse
cli
argparse
subcommands
Intermediate
6 steps
go
package main import ( "errors"
Parsing and validating CLI flags in Go
cli-parsing
validation
error-handling
Intermediate
8 steps
ruby
require "csv" class SalesReport def initialize(path)
Aggregating CSV sales data in Ruby
data-aggregation
memoization
group_by
Intermediate
6 steps
javascript
'use server' import { revalidatePath } from 'next/cache' import { redirect } from 'next/navigation'
How a Next.js Server Action updates a post
server-actions
authorization
validation
Intermediate
7 steps
ruby
module DurationFormatter UNITS = [ ['week', 604_800], ['day', 86_400],
Turning seconds into human-readable durations in Ruby
greedy-decomposition
modular-arithmetic
formatting
Intermediate
7 steps
php
<?php namespace App\Support;
Merging query params onto a URL in PHP
url-parsing
query-strings
immutability
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/parsing-cli-options-with-optionparser-explained-ruby-3b8b/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.