例如,当我在命令行中键入ruby file.rb -a "water the plants"
时我想把这一行添加到散列中。比如待办事项列表。所以它看起来像item1: water the plants
以下是我迄今为止所做的:
require 'optparse'
option_parser = OptionParser.new do |opts|
opts.on '-a', '--add',
end
提前感谢!
仔细查看OptionParser文档中的示例。
要接受参数的值,您必须在opts.on
的第二个参数中指定它,如下所示:
require 'optparse'
option_parser = OptionParser.new do |opts|
opts.on '-a', '--add val' do |value|
puts value
end
end.parse!
要使其成为必需的参数,只需将val
更改为大写的VAL
(它可以是任何单词,我只是用"val"作为示例(。
调用它,你可以看到它是如何工作的:
ruby file.rb -a "water the plants"
# => "water the plants"
ruby file.rb -a "water the plants" "do the dishes"
# => "water the plants"
ruby file.rb -a "water the plants" -a "do the dishes"
# => water the plants
# => do the dishes
如您所见,要传递多个值,需要多次包含-a
标志。对每个值单独调用块。