Really Cheap Command-Line Option Parsing in Ruby

前端 未结 20 1100
野的像风
野的像风 2020-11-30 16:57

EDIT: Please, please, please read the two requirements listed at the bottom of this post before replying. People keep posting their new gems and li

20条回答
  •  情歌与酒
    2020-11-30 17:00

    Since nobody appeared to mention it, and the title does refer to cheap command-line parsing, why not just let the Ruby interpreter do the work for you? If you pass the -s switch (in your shebang, for example), you get dirt-simple switches for free, assigned to single-letter global variables. Here's your example using that switch:

    #!/usr/bin/env ruby -s
    puts "#$0: Quiet=#$q Interactive=#$i, ARGV=#{ARGV.inspect}"
    

    And here's the output when I save that as ./test and chmod it +x:

    $ ./test
    ./test: Quiet= Interactive=, ARGV=[]
    $ ./test -q foo
    ./test: Quiet=true Interactive=, ARGV=["foo"]
    $ ./test -q -i foo bar baz
    ./test: Quiet=true Interactive=true, ARGV=["foo", "bar", "baz"]
    $ ./test -q=very foo
    ./test: Quiet=very Interactive=, ARGV=["foo"]
    

    See ruby -h for details.

    That must be as cheap as it gets. It will raise a NameError if you try a switch like -:, so there's some validation there. Of course, you can't have any switches after a non-switch argument, but if you need something fancy, you really should be using at the minimum OptionParser. In fact, the only thing that annoys me about this technique is that you'll get a warning (if you've enabled them) when accessing an unset global variable, but it's still falsey, so it works just fine for throwaway tools and quick scripts.

    One caveat pointed out by FelipeC in the comments in "How to do really cheap command-line option parsing in Ruby", is that your shell might not support the 3-token shebang; you may need to replace /usr/bin/env ruby -w with the actual path to your ruby (like /usr/local/bin/ruby -w), or run it from a wrapper script, or something.

提交回复
热议问题