2

I am attempting to use OptionParser to read in multiple options and have them all act on a single filename. Ex: myprogram.rb -a -b file.txt How can I make 2 options share a mandatory argument while also allowing things like -h to run without parameters? Currently the above line just makes -a take -b as its parameter.

optionparser.on("-a FILENAME", "Do this") do |a|
  puts a
end
optionparser.on("-b FILENAME", "Do that") do |b|
  puts b
end

EDIT:

What it is doing:

myprogram.rb -a -b file.txt
=> -b

What I need it to do:

myprogram.rb -a -b file.txt
=> file.txt
=> file.txt

Note:

These commands should be able to run independently as well as concurrently similar to ls -a .., ls -l .. and ls -a -l .. However NEITHER command should work if there is no filename given. Ideally this solution should work with any n number of options.

4

1 回答 1

0

我现在拥有的是:

alpha=false
beta=false
optionparser.on("-a", "Do this") do |a|
  alpha = a
end
optionparser.on("-b", "Do that") do |b|
  beta = b
end
if alpha
  #do something with ARGV[0]
end
if beta
  #do something with ARGV[0]
end

这段代码假定在选择选项后,命令行上唯一剩下的应该是文件名。我觉得有一种更优雅的方法可以做到这一点,它考虑到其他可能使命令行混乱的事情,并允许对它们进行纠错。

于 2013-04-04T21:10:03.430 回答