Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Needless Argument in Ruby optparser

I am facing issue with following code for parsing command line options

#!/usr/bin/env ruby
require 'optparse'

options = {:username=>nil}
optparse = OptionParser.new do|opts|
    # Define the options, and what they d
    opts.on( "--username", "Cassandra username" ) do |username|
        options[:username] = username
    end

    opts.on( '--password', 'Cassandra password' ) do |password|
        options[:password] = password
    end

    opts.on( '--keyspace', 'Cassandra keyspace' ) do |keyspace|
        options[:keyspace] = keyspace
    end
end
puts ARGV

optparse.parse!(ARGV)

puts options

When I run this code from commandline as

./testopt.rb --username=uuuuu --password=xxxxxx --keyspace=test

I get following output

--username=uuuuu
--password=xxxxxx
--keyspace=test
./testopt.rb:25:in `<main>': needless argument: --username=uuuuu (OptionParser::NeedlessArgument)

What am missing? I am in ruby 2.2.3p173 (2015-08-18 revision 51636) [x86_64-linux]

Thanks in advance

like image 322
Amit Teli Avatar asked Oct 15 '25 15:10

Amit Teli


1 Answers

Although @mudasobwas answer is not wrong in itself, you can have "option=value" parsing by specifying the option like in the example below (mmh, tested with ruby 2.3.1 only).

Key is to use opts.on('--username=USER',... vs. opts.on('--username',... .

#!/usr/bin/env ruby
require 'optparse'

options = {:username=>nil}
optparse = OptionParser.new do|opts|
    # Define the options, and what they do
    opts.on( "--username=USER", 'Cassandra username' ) do |username|
        options[:username] = username
    end

    opts.on( '--password=PASSWORD', 'Cassandra password' ) do |password|
        options[:password] = password
    end

    opts.on( '--keyspace=KEY', 'Cassandra keyspace' ) do |keyspace|
        options[:keyspace] = keyspace
    end
end
puts ARGV

optparse.parse!(ARGV)

puts options

You do not loose the ability to pass the value without the equal-sign using this approach and have it converted to string:

➜  ~  /tmp/op.rb --username myuser           
--username
myuser
{:username=>"myuser"}
➜  ~  /tmp/op.rb --username=myuser
--username=myuser
{:username=>"myuser"}
like image 84
Felix Avatar answered Oct 18 '25 08:10

Felix



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!