How to use variable arguments with ruby's OptionParser

主宰稳场 提交于 2019-12-03 13:06:57
OPTS = {}

op = OptionParser.new do |x|
    x.banner = 'cat <options> <file>'      
    x.separator ''

    x.on("-A", "--show-all", "Equivalent to -vET")               
        { OPTS[:showall] = true }      

    x.on("-b", "--number-nonblank", "number nonempty output lines") 
        { OPTS[:number_nonblank] = true }      

    x.on("-x", "--start-from NUM", Integer, "Start numbering from NUM")        
        { |n| OPTS[:start_num] = n }

    x.on("-h", "--help", "Show this message") 
        { puts op;  exit }

end

op.parse!(ARGV)

# Example code for dealing with filenames
ARGV.each{ |fn| output_file(OPTS, fn) }

I shall leave other command line operations, as they say, as an exercise for the reader! You get the idea.

(NB: I had to invent a fictional -x parameter to demo passing a value after a flag.)

Update: I should have explained that this will leave ARGV as an array of filenames, assuming that the user has entered any.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!