Ruby + 选项解析器

4
我正在学习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

我哪里做错了?我尝试使用短选项,但结果仍然相同。

2个回答

7
如果你把它改为什么呢:
opts.on("-i", "--ipaddress IPADDRESS", "IP address of the server") do |ipaddr|
  options[:ipaddress] =  ipaddr
end

请注意第二个参数中的IPADDRESS


+1。谢谢。两个答案都是正确的。因此我将接受@Sergey早先按时间顺序发布的答案。 - slayedbylucifer
1
不用谢,虽然我觉得我的答案之前已经发布了。 ;) - zwippie
为了符合惯例,我会在描述(“IPADDRESS”)中使用与长参数语句相同的措辞。 - Felix

4
# Mandatory argument.
  opts.on("-r", "--require LIBRARY",
          "Require the LIBRARY before executing your script") do |lib|
    options.library << lib
  end

我发现这个链接中提到了一个重点:“--require LIBRARY”。

我已经阅读了你发布的内容,只是当时没有注意到它。 - slayedbylucifer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接