The Accidental Rubyist

invalid byte sequence in UTF-8

Modifying choice (command-line parser)

leave a comment »

I liked choice so much, I didn’t want to leave it (I need unparsed args). So I went back to the source code. And then came back to my timeconverter. I realized I could clean up ARGV based on Choice.choices. This worked.

1 module Choice
2   def get_unparsed_args(args)
3     flat=Choice.choices.to_a.flatten
4     args.delete_if { |a| a[0].chr == '-' || a[0,1] == '--' || flat.include?(a) }
5     args
6   end
7 end

If this is a bad idea, please tell me, this is the first time I have tried such a thing. It worked, but I would have copy this to each program. Anyway, I have tested it with only one program which has limited options.

I can call this method giving it ARGV and get back an array with only unparsed options which I could then process in a loop.

So it looks like I will not be evaluating other libraries as of now. I would be grateful if Chris would give us a way of getting the unparsed args. I don’t know how correct this method is. Needs testing in many scenarios.

# substitute “foo” with “bar” ONLY for lines which contain “baz”
$ cat | ruby -pe ‘gsub(/foo/, “bar”) if $_ =~ /baz/’


Written by totalrecall

September 8, 2008 at 10:41 pm

Posted in ruby

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: