Yusuf Husainy
Yusuf Husainy

Reputation: 635

Command line option parsing in Ruby

I have a ruby script that parses command line options given to it as follows:

#!/usr/bin/ruby

require 'optparse'

puts 'Hello World!, This is my first ruby program'

options = {}

optparse = OptionParser.new do|opts|

  opts.banner = "Featbuild minimal trial script for command line parsing"

  options[:cpl] = nil
  opts.on('-cpl SWITCH_STATE', 'compile on or off') do|cplopt|
      options[:cpl] = cplopt
      OPT_CPL=cplopt
      puts cplopt
  end

  opts.on('-h', '--help', 'Display this screen') do
    puts opts
    exit
  end
end

optparse.parse!

output = open("mypipe", "w+")

output.puts OPT_CPL
#output.flush

Now the line opts.on('-cpl SWITCH_STATE', 'compile on or off') do|cplopt| in the above script is where I have a problem.

I believe we can do it in follwoing ways: 1.)opts.on('--cpl SWITCH_STATE', 'compile on or off') do|cplopt| 2.)opts.on('-c', '--cpl SWITCH_STATE', 'compile on or off') do|cplopt| 3.)opts.on('-cpl SWITCH_STATE', 'compile on or off') do|cplopt|

This is what I pass as the arguments that works:

$./try1.rb --cpl on
$./try1.rb -c on

This does not work: $./try1.rb -cpl on

Ruby, instead of getting 'on' as the option argument, gets 'pl', as if $./try.rb -c pl was specified.

I want to have the string $./try1.rb -cpl on be parsed in such a way that 'on' gets passed to the block of the method opts.on() in 'cplopt'.

I was referring to this tutorial: http://ruby.about.com/od/advancedruby/a/optionparser2.htm

It seems '-cpl on' isn't possible in Ruby? Is this so?

What other alternatve solutions can I apply over here?

Upvotes: 1

Views: 210

Answers (2)

Jay
Jay

Reputation: 94

I think you will need to ensure that only cp1 is in the single quotes instead of

-cpl SWITCH_STATE

do

 opts.on('-cpl', 'compile on or off') do|cplopt|
  options[:cpl] = cplopt
  OPT_CPL=cplopt
  puts cplopt
 end

Here is an example:

opts.on('-s', '--size 1G or 1024M', '1G or 1024M') do |s|
    options[:size] = s;
end

Upvotes: 1

Matt
Matt

Reputation: 74680

Try Trollop, as it makes option parsing life easier.

require 'trollop'
opts = Trollop::options do
  version "compile 0.1.0"
  banner  "Usage: compile <option> - where [options] are:"
  opt     :cpl,  "compile on or off",  :type => :string,  :default => "off"
end
puts opts.cpl

When run, results in:

$ ruby ./trollop.rb --cpl on
on

$ ruby ./trollop.rb --cpl off
off

$ ruby ./trollop.rb -c on
on

$ ruby ./trollop.rb -c off
off

$ ruby ./trollop.rb
off


Trollop 2.0 supports no- negation of boolean options which you might find easier than dealing with the on/off strings.

opt "cpl", "Compile", :default => true

When run, results in:

$ ruby trollop.rb --cpl
true

$ ruby trollop.rb --no-cpl
false

Upvotes: 1

Related Questions