【问题标题】:Ruby + Option parserRuby + 选项解析器
【发布时间】:2013-12-04 12:09:45
【问题描述】:

我正在通过引用thisthis 来学习Ruby 中的选项解析。这是我的测试代码:

#!/usr/bin/ruby
require "optparse"

options = {}

optparse = OptionParser.new do |opts|
  opts.banner = "Learning Option parsing in Ruby"

  opts.on("-i", "--ipaddress", "IP address of the server") do |ipaddr|
    options[:ipaddress] =  ipaddr
  end

    opts.on("-u", "--username", "username to log in") do |user|
      options[:username] = user
    end

    opts.on("-p", "--password", "password of the user") do |pass|
      options[:password] = pass
    end
end

optparse.parse!

puts "the IPaddress is #{options[:ipaddress]}" if options[:ipaddress]
puts "the username is #{options[:username]}" if options[:username]
puts "the password is #{options[:password]}" if options[:password]

我的目的是打印我传递给脚本的选项。但是,它不会打印我通过的选项,而只是说true

# ruby getops.rb  --ipaddress 1.1.1.1
the IPaddress is true
# ruby getops.rb  --username user1
the username is true
# ruby getops.rb  --password secret
the password is true

我哪里错了?我也尝试了短选项,但结果是一样的。

【问题讨论】:

    标签: ruby


    【解决方案1】:

    如果你把它改成:

    opts.on("-i", "--ipaddress IPADDRESS", "IP address of the server") do |ipaddr|
      options[:ipaddress] =  ipaddr
    end
    

    注意第二个参数中的IPADDRESS

    【讨论】:

    • +1。谢谢。两个答案都是正确的。因此,我将接受@Sergey 之前按时间顺序发布的那个。
    • 不客气,虽然我认为我的回答是之前的海报。 ;)
    • 我会——为了约定——在描述(“IPADDRESS”)中使用与长参数语句中相同的措辞。
    【解决方案2】:
    # Mandatory argument.
      opts.on("-r", "--require LIBRARY",
              "Require the LIBRARY before executing your script") do |lib|
        options.library << lib
      end
    

    我在您的第一个链接中发现了这一点。注意“--require LIBRARY”。

    【讨论】:

    • 正确。我已经阅读了您发布的内容。只是我没注意而已。
    猜你喜欢
    • 2013-05-16
    • 2011-07-08
    • 1970-01-01
    • 2013-10-03
    • 2020-09-03
    • 2013-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多