如何在ruby的OptionParser中使用变量参数 [英] How to use variable arguments with ruby's OptionParser

查看:125
本文介绍了如何在ruby的OptionParser中使用变量参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不太了解ruby,但是我正在尝试为同事编写的脚本添加一些功能.

I don't know ruby very well, but I'm trying to add some functionality to this script a co-worker wrote.

基本上现在,它接受一些标志和standard作为输入,并使用OptionParser解析标志.

Basically right now it takes a few flags and standard in as input, and it uses OptionParser to parse the flags.

我想使用OptionParser来解析与cat类似的命令行参数选择.所以我想我的问题是我该如何使用OptionParser编写在ruby中解析cat的命令行选项

I want to use OptionParser to parse a selection of command line arguments similar to those of cat. So I guess my question is how would I write the command line options parsing part of cat in ruby using OptionParser

cat [OPTION]... [FILE]...

希望如此,任何帮助都将得到感谢.

Hope that makes sense, any help is appreciated.

推荐答案

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.

(注意:我必须发明一个虚构的-x参数来演示在标志后传递值.)

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

更新:我应该已经解释说,假设用户输入了任何内容,这会将ARGV保留为文件名数组.

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

这篇关于如何在ruby的OptionParser中使用变量参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆