我正在学习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
我哪里做错了?我尝试使用短选项,但结果仍然相同。