Ruby_命令行参数解析工具_工具类

 

一。用命令行的ARGV 和ARGF和ENV

写一些工具类和脚本的时候总是要用到合理的命令行参数解析,稍微复杂一点就不能用ARGV了。

关于这两个的简单用法,请看一篇文章。

 

二。找个好用的工具吧~

 

require 'optparse'

这个工具感觉不是太好用。

 

三。使用trollop工具

这个工具很好用哦,能力也很强,可以解析形式如svn命令行一样的参数,如svn delete xxx_files

这个工具现在的缺点,如果说是的话,就是参数和值不能连写,例如 -f xxx_file_name 这么写没有问题,但是如果写为 -fxxx_file_name 那么解析不出来。不过这不算是问题了,你可以处理一下,把这种形式的参数分开就ok了~

 

看个例子:

Examples

Simple

 

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 nil
end

p 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

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值