vkill'blog

“技术本身没有太多价值,掌握了新的思考方式才是真的收获”
Pages: 1/1 First page 1 Final page [ View by Articles | List ]
假设我们需求如下

Usage: test.rb [OPTION]
-h,  --help               view help
-e                        encode String (default)
-d                        decode String
-p,  --pass=PASSWD  password


ruby 1.8.x win一键安装时我们是这样写

require 'getopts'
getopts('hed', 'help', 'p:', 'pass:')
p $OPT


到了ruby 1.9.1 时应该这样写,详细参见 lib\ruby\gems\1.9.1\gems\getopt-1.4.0\examples\目录下的两个说明文件

#gem install getopt  -v 1.4.0
require "getopt/long"
opts = Getopt::Long.getopts(
  ["--help", "-h"],
  ["-e"],
  ["-d"],
  ["--pass", "-p", 0]
)
p opts


注:上例中 ["--pass", "-p", 0] 那句按官方example的写法应该是 ["--pass", "-p", REQUIRED],但是那样写的话就会报错如下:uninitialized constant REQUIRED (NameError) ,我看了 lib\getopt\long.rb 文件中有如下设置

REQUIRED  = 0 # Argument is required if switch is provided.
BOOLEAN   = 1 # Value of argument is true if provided, false otherwise.
OPTIONAL  = 2 # Argument is optional if switch is provided.
INCREMENT = 3 # Argument is incremented by 1 each time the switch appears.

所以这里我们写为0就可以使用了

后记:个人感觉还是 getopts 好,我是从1.8.7 复制了个 getopts.rb 到了 \lib\ruby\1.9.1 目录下了,呵呵
类别:ruby & rails | Tags: , , , , | 0 条评论, 1156 次阅读
Jan
25
2010
请多提意见,我好修复完善

v0.1 (20100120)
原理参见 EncryptStr_TBySCW.rb

类别:ruby & rails | Tags: , , , , | 1 条评论, 1520 次阅读
Jan
20
2010
Pages: 1/1 First page 1 Final page [ View by Articles | List ]