2

I'm trying to take the argument values using OptionParser. Instead of values, my code is returning only boolean:

require 'optparse'

options ={}
opts = OptionParser.new do |opts|
opts.on('-v')    { |version| options[:version] = version }
opts.on('-g')    { |branch| options[:branch] = branch }
opts.on('-f')    { |full| options[:full] = full }
opts.on('-h')    { RDoc::usage }
end.parse!

# mandatory options
if (options[:version] == nil)  or (options[:branch] == nil) or (options[:full]== nil) then
    puts options[:branch]
    puts options[:version]
    puts options[:full]
    RDoc::usage('usage')
end

puts options[:branch]

---> TRUE

Any idea?

1 Answer 1

4

If you want to capture a value you need to ask for it:

opts = OptionParser.new do |opts|
opts.on('-v=s') { |version| options[:version] = version }
opts.on('-g=s') { |branch| options[:branch] = branch }
opts.on('-f=s') { |full| options[:full] = full }
opts.on('-h') { RDoc::usage }

The =s notation means there's an associated value.

When defining interfaces like this don't forget to include long-form names for clarity like --version or --branch so people don't have to remember g means "branch".

All of this is covered in the fantastic documentation which I encourage you to read.

Sign up to request clarification or add additional context in comments.

4 Comments

Also, of course, the term 's' should be replaced with something meaningful, e.g. 'branch' for '-g'. Remember that the help text will be created using these option specifications.
Also, as an aside, OpenStructs are great for storing these options. No need to explicitly refer to hash keys nor to specify in advance attribute names (as would be necessary with Struct.
@KeithBennett A great point there. Like --version=version is better than -v=s. OpenStruct can keep things pretty clean if you like, but there's nothing entirely wrong with a regular Hash.
really fantastic document, +1 :)))))))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.