Ruby_命令行参数解析工具_工具类
?
一。用命令行的ARGV 和ARGF和ENV
写一些工具类和脚本的时候总是要用到合理的命令行参数解析,稍微复杂一点就不能用ARGV了。
关于这两个的简单用法,请看一篇文章。
?
二。找个好用的工具吧~
?
require 'optparse'
这个工具感觉不是太好用。
?
三。使用trollop工具
这个工具很好用哦,能力也很强,可以解析形式如svn命令行一样的参数,如svn delete xxx_files
这个工具现在的缺点,如果说是的话,就是参数和值不能连写,例如 -f xxx_file_name 这么写没有问题,但是如果写为 -fxxx_file_name 那么解析不出来。不过这不算是问题了,你可以处理一下,把这种形式的参数分开就ok了~
?
看个例子:
ExamplesSimple?
require 'trollop'opts = Trollop::options do opt :monkey, "Use monkey mode" # flag --monkey, default false opt :goat, "Use goat mode", :default => true # flag --goat, default true opt :num_limbs, "Number of limbs", :default => 4 # integer --num-limbs <i>, default to 4? opt :num_thumbs, "Number of thumbs", :type => :int # integer --num-thumbs <i>, default nilendp opts # a hash: { :monkey => false, :goat => true, :num_limbs => 4, :num_thumbs => nil }#注意#1 默认是boolean类型的,所以只需要-m 不需要后面的值;#? ?如果没有-m,这用默认值;如果没有默认值,则默认是false#2 如果给值了,则结果的hash会多一个键值对,在键名为:xxx_given,值为:true?Trollop::options returns a hash of values. That's all the output you get.Underscores are converted to dashes. opt :hello_there corresponds to an option --hello-there.All options are taken to be boolean flags, defaulting to false, unless you specify a default or a type. The type will be inferred from the default if given, so no need to specify both.Short (one-character) option names are created automatically. You can set them manually with :short.?
更详细的使用文档,看官方吧~
http://trollop.rubyforge.org/
http://all-thing.net/label/trollop
?
?
?
?
?