user3472065 user3472065 - 7 months ago 32
Ruby Question

in Ruby, OptionParser returns boolean instead of input values

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

require 'optparse'

options ={}
opts = 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 }

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

puts options[:branch]

---> TRUE

Any idea?


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

opts = 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.