简体   繁体   中英

Ruby Options parser not reading command line options

Im trying to use the Ruby builtin options parser

I have this file

File parser.rb #!/usr/bin/env ruby require 'optparse' require 'pp'

 class parser

 def initialize(args)
 @options = Hash.new()
 @op = OptionParser.new do |opts|
 @options[:verbose] = false
opts.on('-v', '--verbose', 'Output more information') do 
    @options[:verbose] = true
end

@options[:quick] = false
opts.on( '-q', '--quick', 'Perform the task quickly' ) do 
    @options[:quick] = true
end

@options[:logfile] = nil
opts.on( '-l', '--logfile FILE', 'Write log to FILE' ) do|file|
           @options[:logfile] = file
end

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

    @options[:sID] = "-1"
opts.on('-sID', '--senderID', 'Sender ID used by device') do |sID|
     @options[:sID] = sID
end

@options[:rID] = "-1"
opts.on('-rID', '--receiverID', 'Receiver ID used by device') do |rID|
    @options[:rID] = rID
end

  @op.parse!
  @op
  end

 def getOptionsHash
 @options
  end

then Im trying to use this class in the file below

 #!/usr/bin/env ruby

 # Setup Bundler
 require 'rubygems'
 require 'bundler/setup'

 require_relative 'parser'


 #Variables in the options hash in parser.rb

 op = Parser.new(ARGV)
 pp op.getOptionsHash()

when I run this on the command line without args it uses default values: ./push_test.rb

I get the following output:

 {:verbose=>false,
  :quick=>false,
   :logfile=>nil,
  :sID=>"-1",
  :rID=>"-1",

  }

when I run this on the command line with args: ./push_test.rb -sID "33"

I get the following output:

  {:verbose=>false,
   :quick=>false,
   :logfile=>nil,
  :sID=>"ID",
  :rID=>"-1",

  }

Why is the sID not being set to 33?

Can anyone help please?Ive tried to figure this out but cant make any headway

Seems the short switch has to be a single character -s

./push_test.rb -sID "33"

outputs:

{:verbose=>false, :quick=>false, :logfile=>nil, :sID=>"ID", :rID=>"-1" }

because everything after -s to the first white space will be assigned to :sID, in your case its the word "ID" that follows "-s", hence you are getting :sID =>"ID"

./push_test.rb -s "33" will do the trick.

From the OptParser docs :

 Short style switch:: Specifies short style switch which takes a mandatory, optional or no argument. It's a string of the following form: "-xMANDATORY" "-x[OPTIONAL]" "-x" 

So at specifying switch -sID you define switch -s with argument named ID - something different than you were probably expecting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM