Really Cheap Command-Line Option Parsing in Ruby

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

    If you want a simple command line parser for key/value commands without the use of gems:

    But this only works if you always have key/value pairs.

    # example
    # script.rb -u username -p mypass
    
    # check if there are even set of params given
    if ARGV.count.odd? 
        puts 'invalid number of arguments'
        exit 1
    end
    
    # holds key/value pair of cl params {key1 => value1, key2 => valye2, ...}
    opts = {} 
    
    (ARGV.count/2).times do |i|
        k,v = ARGV.shift(2)
        opts[k] = v # create k/v pair
    end
    
    # set defaults if no params are given
    opts['-u'] ||= 'root'
    
    # example use of opts
    puts "username:#{opts['-u']} password:#{opts['-p']}"
    

    If you don't' need any checking you could just use:

    opts = {} 
    
    (ARGV.count/2).times do |i|
        k,v = ARGV.shift(2)
        opts[k] = v # create k/v pair
    end
    

提交回复
热议问题