Confusing option parser

The first one is quite normal, works as expected.

OptionParser.parse do |parser|
  parser.on("-h", "--help", "Show config help") do
    puts "config --help"
    exit
  end
  parser.on("-v", "--version", "Print the version") do
    puts "config --version"
    exit
  end
end

The second will exit directly, which indicates the program doesn’t execute in sequence but following a nested order.

OptionParser.parse do |parser|
  parser.on("-h", "--help", "Show config help") do
    puts "config --help"
  end
  parser.on("-v", "--version", "Print the version") do
    puts "config --version"
  end
  exit
end

The block passed to OptionParser.parse is meant to configure the option parser instance. The actual parsing starts after the entire block has completed.

Your code is equivalent to this:

parser = OptionParser.new
parser.on("-h", "--help", "Show config help") do
  puts "config --help"
end
parser.on("-v", "--version", "Print the version") do
  puts "config --version"
end
exit
parser.parse

Note that parse is called after exit, so it never happens.

OptionParser#on registers the block as a handler which is used when the option name matches while executing parse.

1 Like