假设我们需求如下
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 目录下了,呵呵
Last modified by vkill on2010/01/25 22:00
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 目录下了,呵呵
Last modified by vkill on2010/01/25 22:00
网友评论(0):


