代码之家  ›  专栏  ›  技术社区  ›  JasonBorne

当没有给定ARGV时,设置标志并运行默认值

  •  1
  • JasonBorne  · 技术社区  · 8 年前

    我一直在想如何使用 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 回复  |  直到 6 年前
        1
  •  1
  •   br3nt    8 年前

    由于以下原因,文件提前退出: $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