由于以下原因,文件提前退出:
$help = usage
这个
usage
方法具有以下命令
exit
这使得脚本输出使用文本,然后退出。
一旦你过去了
loop { ... }
将导致程序永远运行,因为它是一个无限循环。
我想你想要的是这样的东西:
def usage
$stderr.puts("Usage: #{File.basename(__FILE__)}: [-f|u] <file/path/>")
end
def say_hi(name)
puts "Hi #{name}! How are you?!"
end
args = ARGV.dup
arg = args.shift # get the flag
case arg
when '-f'
file = args.shift
puts "doing something with #{file}"
when '-h'
usage
else
say_hi("John")
end
但是,如果您希望用户能够解析多个args和flags等等,那么您可以使用while循环来解析args:
args = ARGV.dup
names = []
# parse all of the args
while (flag = args.shift)
case flag
when '-f'
file = args.shift
when '-h'
# this will cause the program to exit if the help flag is found
usage
exit
else
# this isn't a flag, lets add it to the list of things to say hi to
names << flag
end
end
if names.empty?
say_hi("John")
else
names.each {|name| say_hi(name) }
end