7
7stud --
Here's a simple example that looks for two options--one with a required
value and one with an optional value:
require 'optparse'
opts = OptionParser.new do |opts|
puts 'hello'
#option where value is required:
opts.on("-t=RANDOM_CHARS") do |val|
puts 'in first on()'
puts "-t option entered with value=#{val}"
end
#option where value is optional:
opts.on("-y [=RANDOM_CHARS]") do |val|
puts "-y option entered with value=#{val}"
end
end
opts.parse!
p ARGV
--output:--
$ruby optparseEx2.rb -t hi -y
hello
in first on()
-t option entered with value=hi
-y option entered with value=
[]
However, when I change the line:
opts.parse!
to:
opts.parse
I get this output:
$ruby optparseEx2.rb -t hi -y
hello
["-t", "hi", "-y"]
which indicates that none of the on() handlers executed. My reading of
parse() is that it's the same as parse!() except that parse() doesn't
remove the option/values from ARGV.
value and one with an optional value:
require 'optparse'
opts = OptionParser.new do |opts|
puts 'hello'
#option where value is required:
opts.on("-t=RANDOM_CHARS") do |val|
puts 'in first on()'
puts "-t option entered with value=#{val}"
end
#option where value is optional:
opts.on("-y [=RANDOM_CHARS]") do |val|
puts "-y option entered with value=#{val}"
end
end
opts.parse!
p ARGV
--output:--
$ruby optparseEx2.rb -t hi -y
hello
in first on()
-t option entered with value=hi
-y option entered with value=
[]
However, when I change the line:
opts.parse!
to:
opts.parse
I get this output:
$ruby optparseEx2.rb -t hi -y
hello
["-t", "hi", "-y"]
which indicates that none of the on() handlers executed. My reading of
parse() is that it's the same as parse!() except that parse() doesn't
remove the option/values from ARGV.