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
After_Save Callback to Set The Updated_By Column to The Current_User
Rake Cucumber and Rake Spec Always Use "Develop" Environment
Escaping Strings for Ruby Sqlite Insert
How to Use C# Style Enumerations in Ruby
How to Handle 404 Not Found Errors in Nokogiri
Rails/Postgres, 'Foreign Keys' Stored in Array to Create 1-Many Association
Does The Rails Orm Limit The Ability to Perform Aggregations
Without Converting to a String, How Many Digits Does a Fixnum Have
How to Remove Ruby on Rails 4 Beta
Capybara-Webkit: Automatically Save a Screenshot on an Rspec Test Failure
Why Does Including This Module Not Override a Dynamically-Generated Method
How to Find Word with The Greatest Number of Repeated Letters
How to Test If a Value Is a Prime Number in Ruby? Both The Easy and The Hard Way
Functional Testing of a Restful Post in Ruby on Rails