G B G B - 2 months ago 8
Ruby Question

Ruby example with exclamation mark

I am writing a script with different options in ruby, and I can't understand how the OptionParser could help me.

In particular, there is an example in the documentation: https://docs.ruby-lang.org/en/2.1.0/OptionParser.html

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


I can understand the exclamation mark on the "end.parse" line (but I expected a parameter after that), but I find the following 2 lines confusing,
p
hasn't been declared, and I can't understand if it's part of the example source.

And how do I use the '-v' option? Do I simply check if options[:v] is
nil
or
true
?

Last thing, what happens to the other options? Does the OptionParser only parse switches? What if I had other parameters after the '-v'? Like
myscript -v duck ketchup banana
?

Answer

To answer your questions:

I can understand the exclamation mark on the "end.parse" line (but I expected a parameter after that)

The documentation states that parse! takes an optional argv parameter. If it is not supplied, it defaults to default_argv, which I imagine is the string containing the arguments passed to this script in the command line.

p hasn't been declared, and I can't understand if it's part of the example source

p is defined in Kernel, so it is (almost) always available in Ruby. p obj is equivalent to puts obj.inspect.

In this context, p is just used to illustrate that after parsing the arguments, the options hash contains all the flags/options you defined in the OptionParser block.

And how do I use the '-v' option? Do I simply check if options[:v] is nil or true?

Yes, but that would actually be options[:verbose].

Last thing, what happens to the other options? Does the OptionParser only parse switches? What if I had other parameters after the '-v'? Like myscript -v duck ketchup banana?

You will have to make multiple calls to opts.on to match all the other switches/arguments you are interested in. Look at the documentation here for explanations on how to do that.