Optparse: parse v. parse!?

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.

Hi,

At Wed, 20 Feb 2008 11:57:09 +0900,
7stud – wrote in [ruby-talk:291731]:

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.

No, parse doesn’t have default arguments. This hasn’t changed
since it was imported.

Nobuyoshi N. wrote:

Hi,

At Wed, 20 Feb 2008 11:57:09 +0900,
7stud – wrote in [ruby-talk:291731]:

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.

No, parse doesn’t have default arguments.

Huh?

7stud – wrote:

Nobuyoshi N. wrote:

Hi,

At Wed, 20 Feb 2008 11:57:09 +0900,
7stud – wrote in [ruby-talk:291731]:

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.

No, parse doesn’t have default arguments.

Huh?

Well, after scanning through the docs again, I found this in one of the
examples:

options = OptparseExample.parse(ARGV)

…and now your cryptic post makes sense.

Usage

opts.parse! #removes options/values from ARGV

opts.parse(ARGV) #doesn’t change ARGV