当没有给出ARGV时,制作标志并运行默认值

时间:2016-04-08 02:16:41

标签: ruby flags 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?!

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

该文件由于以下行而提前退出:$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

但是如果你期望用户能够解析多个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