当 none 被赋予 ARGV 时,使标志和 运行 默认

Making flags and running default when none are given ARGV

我一直在尝试弄清楚如何使用 ARGV 制作标志(我知道 optparser,我不想使用它)

我想做的是制作一个标志来加载文件,并制作一个标志来显示帮助,如果没有给出标志,我想 运行 程序保持原样..

示例say_hi.rb:

def usage
  $stderr.puts("Usage: #{File.basename}: [-f|u] <file/path/>")
  exit
end

$file = nil
$help = usage

loop { case ARGV[0]
         when '-f' then  ARGV.shift; $file = ARGV.shift
         when '-h' then  ARGV.shift; $help = ARGV.shift
         else
           #No flag given, run program with "John" as the method argument

end }

def say_hi(name)
  puts "Hi #{name}! How are you?!"
end

say_hi("John")

当前输出:

C:\Users\Jason\MyScripts>ruby say_hi.rb
Usage: say_hi.rb: [-f|u] <file/path/>

C:\Users\Jason\MyScripts>ruby say_hi.rb -f john.txt
Usage: say_hi.rb: [-f|u] <file/path/>

C:\Users\Jason\MyScripts>ruby sayhi.rb -h
Usage: say_hi.rb: [-f|u] <file/path/>

john.txt:

John

预期输出:

#running without flag =>
ruby say_hi.rb
#<= Hi John! How are you?!

#running with -h flag(help) =>
ruby say_hi -h
#<= Usage: say_hi: [-f|u] <file/path/>

#running with the -f flag(file) =>
ruby say_hi -f temp/name_file.txt
#<= Hi John! How are you?!

我怎样才能做到这一点?

由于这一行,文件提前退出:$help = usageusage 方法有命令 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

但是,如果您希望用户能够解析多个参数和标志等等,那么您可以使用 while 循环来解析参数:

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