How to Use Variable Arguments with Ruby's Optionparser

How to use variable arguments with ruby's OptionParser

OPTS = {}

op = OptionParser.new do |x|
x.banner = 'cat <options> <file>'
x.separator ''

x.on("-A", "--show-all", "Equivalent to -vET")
{ OPTS[:showall] = true }

x.on("-b", "--number-nonblank", "number nonempty output lines")
{ OPTS[:number_nonblank] = true }

x.on("-x", "--start-from NUM", Integer, "Start numbering from NUM")
{ |n| OPTS[:start_num] = n }

x.on("-h", "--help", "Show this message")
{ puts op; exit }

end

op.parse!(ARGV)

# Example code for dealing with filenames
ARGV.each{ |fn| output_file(OPTS, fn) }

I shall leave other command line operations, as they say, as an exercise for the reader! You get the idea.

(NB: I had to invent a fictional -x parameter to demo passing a value after a flag.)

Update: I should have explained that this will leave ARGV as an array of filenames, assuming that the user has entered any.

How to parse an argument without a name with Ruby's optparse

First parse! with optparse, then scan the ARGV and raise if ARGV is empty. Like so:

op.parse!
filename = ARGV.pop
raise "Need to specify a file to process" unless filename

The mandatory filename will not be processed by the OptionParser and will be left for you in ARGV - if it's not there, just raise manually.

Ruby OptionParser: how to handle arguments without a prefix (like a required filename)

OptionParser specifically handles options - that is, things starting with dashes. After it parses, the remaining arguments are left in ARGV. You can check for your filename there and exit with an error if it's missing.

With a slight modification on their minimal example,

require 'optparse'

options = {}
OptionParser.new do |opts|
opts.banner = "Usage: example.rb [options]"

opts.on("-v", "--[no-]verbose", "Run verbosely") do |v|
options[:verbose] = v
end
end.parse!

p options
p ARGV
p "Where is my hat?!" if ARGV.length == 0

You get this:

$ ruby parse.rb
{}
[]
"Where is my hat?!"

$ ruby parse.rb hat
{}
["hat"]

$ ruby parse.rb -v hat
{:verbose=>true}
["hat"]

Suppress short arguments with OptionParser

Just drop the short form:

require 'optparse'

OptionParser.new do |opts|
opts.on("--dangerous-option", "Set dangerous option") do |v|
puts "dangerous option set to #{v}"
end
end.parse!

 

$ ruby foo.rb -h
Usage: foo [options]
--dangerous-option Set dangerous option

$ ruby foo.rb --dangerous-option
dangerous option set to true

Simple explanation for this optparse example from Ruby

The end.parse! is not some magical kind of end if that's what you were thinking. It can be written like this:

option_parser = OptionParser.new do |opts|
opts.banner = "Usage: example.rb [options]"

opts.on("-v", "--[no-]verbose", "Run verbosely") do |v|
options[:verbose] = v
end
end

option_parser.parse!

Set up default option handler for ruby's OptionParser

There's probably a slick way to do it, but I don't know it. I've done this:

  opts = OptionParser.new
...
opts.on_tail("-h", "--help",
"Show this message") do
puts opts
exit
end
begin
opts.parse!(argv)
rescue OptionParser::InvalidOption => e
puts e
puts opts
exit(1)
end


Related Topics



Leave a reply



Submit