Really Cheap Command-Line Option Parsing in Ruby

前端 未结 20 1124
野的像风
野的像风 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:06

    https://github.com/soveran/clap

    other_args = Clap.run ARGV,
      "-s" => lambda { |s| switch = s },
      "-o" => lambda { other = true }
    

    46LOC (at 1.0.0), no dependency on external option parser. Gets the job done. Probably not as full featured as others, but it's 46LOC.

    If you check the code you can pretty easily duplicate the underlying technique -- assign lambdas and use the arity to ensure the proper number of args follow the flag if you really don't want an external library.

    Simple. Cheap.


    EDIT: the underlying concept boiled down as I suppose you might copy/paste it into a script to make a reasonable command line parser. It's definitely not something I would commit to memory, but using the lambda arity as a cheap parser is a novel idea:

    flag = false
    option = nil
    opts = {
      "--flag" => ->() { flag = true },
      "--option" => ->(v) { option = v }
    }
    
    argv = ARGV
    args = []
    
    while argv.any?
      item = argv.shift
      flag = opts[item]
    
      if flag
        raise ArgumentError if argv.size < arity
        flag.call(*argv.shift(arity))
      else
        args << item
      end
    end
    
    # ...do stuff...
    

提交回复
热议问题