A subcommand lets one program route to several related actions.

subcommand `case` is a compact way to map the first argument to a command handler.

Subcommand Dispatch

args
subcommand_dispatch.rb
Replay: real traced execution (multi-file project)
args = ["status"]
subcommand = args.first || "help"

message = case subcommand
when "init"
  "create project"
when "status"
  "show status"
else
  "show help"
end

handled = ["init", "status"].include?(subcommand)

puts "subcommand=#{subcommand}"
puts "message=#{message}"
puts "handled=#{handled}"
args = ["init"]
subcommand = args.first || "help"

message = case subcommand
when "init"
  "create project"
when "status"
  "show status"
else
  "show help"
end

handled = ["init", "status"].include?(subcommand)

puts "subcommand=#{subcommand}"
puts "message=#{message}"
puts "handled=#{handled}"
args = ["unknown"]
subcommand = args.first || "help"

message = case subcommand
when "init"
  "create project"
when "status"
  "show status"
else
  "show help"
end

handled = ["init", "status"].include?(subcommand)

puts "subcommand=#{subcommand}"
puts "message=#{message}"
puts "handled=#{handled}"
  1. args ← ["status"], subcommand ← status, message ← show status

    1args→ ["status"] = ["status"]  #@args=["init"], ["unknown"]2subcommand→ status = args.firststatus || "help"34message→ show status = case subcommandstatus5when "init"6  "create project"7when "status"8  "show status"9else10  "show help"11end1213handled→ true = ["init", "status"].include?(subcommand)true1415puts "subcommand=#{subcommandstatus}"16puts "message=#{messageshow status}"17puts "handled=#{handledtrue}"
    outputsubcommand=status
    message=show status
    handled=true
  1. args ← ["init"], subcommand ← init, message ← create project, handled ← true

    1args→ ["init"] = ["init"]2subcommand→ init = args.firstinit || "help"34message→ create project = case subcommandinit5when "init"6  "create project"7when "status"8  "show status"9else10  "show help"11end1213handled→ true = ["init", "status"].include?(subcommand)true1415puts "subcommand=#{subcommandinit}"16puts "message=#{messagecreate project}"17puts "handled=#{handledtrue}"
    outputsubcommand=init
    message=create project
    handled=true
  1. args ← ["unknown"], subcommand ← unknown, message ← show help

    1args→ ["unknown"] = ["unknown"]2subcommand→ unknown = args.firstunknown || "help"34message→ show help = case subcommandunknown5when "init"6  "create project"7when "status"8  "show status"9else10  "show help"11end1213handled→ false = ["init", "status"].include?(subcommand)false1415puts "subcommand=#{subcommandunknown}"16puts "message=#{messageshow help}"17puts "handled=#{handledfalse}"
    outputsubcommand=unknown
    message=show help
    handled=false