我需要在
Ruby中使用getoptlong类的帮助.我需要执行命令prog_name.ruby -u -i -s filename.到目前为止,我只能用prog_name.ruby -u filename -i filename -s filename执行它.
这是我的getoptlong代码:
require 'getoptlong' class CommonLog parser = GetoptLong.new parser.set_options(["-h","--help",GetoptLong::NO_ARGUMENT],["-u","--url",["-i","--ip",["-s","--stat",GetoptLong::NO_ARGUMENT]) begin begin opt,arg = parser.get_option break if not opt case opt when "-h" || "--help" puts "Usage: -u filename" puts "Usage: -i filename" puts "Usage: -s filename" exit when "-u" || "--url" log = CommonLog.new(ARGV[0]) log.urlReport when "-i" || "--ip" log = CommonLog.new(ARGV[0]) log.ipReport when "-s" || "--stat" log = CommonLog.new(ARGV[0]) log.statReport end rescue => err puts "#{err.class()}: #{err.message}" puts "Usage: -h -u -i -s filename" exit end end while 1 if ARGV[0] == nil || ARGV.size != 1 puts "invalid! option and filename required" puts "usage: -h -u -i -s filename" end
解决方法
我将通过推荐查看新的“
slop”宝石来回答.它是getoptlong的包装器.
如果你正在使用RVM,你可以使用gem install slop,否则你可以使用sudo gem install slop.
GetOptLong是非常强大的,但是,尽管我已经多次使用它,但我仍然需要每次都查看文档.
如果你想要更多的功能,使用“比GetOptLong更容易使用的界面”,请查看Ruby的OptionParser
.你需要更好地计算逻辑,但这是转换代码的快速通道.我不得不为CommonLog gem创建一个类,因为我没有使用它.重要的东西是从ARGV拉出日志的行:
require 'optparse' class CommonLog def initialize(*args); end def urlReport(); puts "running urlReport()"; end def ipReport(); puts "running ipReport()"; end def statReport(arg); puts "running statReport(#{arg})"; end end log = CommonLog.new(ARGV[0]) OptionParser.new { |opts| opts.banner = "Usage: #{File.basename($0)} -u -i -s filename" opts.on( '-u','--[no-]url','some short text describing URL') do log.urlReport() end opts.on('-i','--[no-]ip','some short text describing IP') do log.ipReport() end opts.on('-s','--stat FILENAME','some short text describing STAT') do |arg| log.statReport(arg) end }.parse!
>何时可以写出语句:何时“-h”,“ – help”>如果ARGV [0] == nil || ARGV.size!= 1是错综复杂的.研究ARGV和阵列的工作原理.通常,对于ARGV [0]为零,将不再有参数,所以ARGV.empty?可能就够了.