8

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

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

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.

3
  • Are you asking how to deal with the non-switch ([FILE]) arguments? Commented Mar 2, 2010 at 17:35
  • Yes, I was able to write code for all of the switch options, but I don't know how to deal with the infinite number of files listed after that. Sorry I was unclear. Commented Mar 2, 2010 at 17:43
  • Sorry, I've updated my answer. After parsing all the options, you should be left with ARGV as an array of filenames. Assuming that the user has entered a valid commandline, that is. Commented Mar 2, 2010 at 17:45

1 Answer 1

9
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.

Sign up to request clarification or add additional context in comments.

3 Comments

So the issue with this is it supports only one file. What I'm really trying to figure out is how to deal with the fact that there is 4 files on command line. Lets say a call like "cat a.txt b.txt c.txt d.txt".
Nope, ARGV should be an array with one element for each word left on the command line after the options are processed. In your example it would have four elements.
@icco puts ARGV.inspect # => ["a.txt", "b.txt", "c.txt", "d.txt"]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.