你能告诉我一个快速工作的代码片段来解决这个命令行选项吗?

时间:2009-12-29 13:43:21

标签: ruby command-line

从命令行运行我的脚本时,我希望能够支持这样的事情:

script.rb -n 2 -t first.txt -t second.txt

我希望能够使用1个或更多t个开关,但我不知道如何实现这一目标。我不想这样做:

script.rb -n 2 -tfirst.txt,second.txt

有什么想法吗?

1 个答案:

答案 0 :(得分:7)

您可能希望使用OptionParser http://ruby-doc.org/stdlib/libdoc/optparse/rdoc/classes/OptionParser.html

这样的事情会起作用吗?

require 'optparse'
files = []

OptionParser.new do |opts|
  opts.on("-t", "--text-file TEXTFILE","Text file to run against" ) do |text_file_name|
   files << text_file_name
  end
end.parse!

puts files.inspect