Ruby + Option解析器

 mobiledu2502930381 发布于 2023-02-12 20:57

我正在通过引用这个和这个来学习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]

我的目的是打印我传递给脚本的opton.但是,它不打印我通过的选项,而只是说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

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

1 个回答
  • 如果将其更改为:

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

    请注意IPADDRESS第二个参数.

    2023-02-12 21:00 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有