Computer Science Canada

Quick Argument Parsing

Author:  DtY [ Sat Jun 06, 2009 7:29 pm ]
Post subject:  Quick Argument Parsing

Well, I'm sure there are huge libraries that do this, and make documentation for you and all that, but here's my quick one:
Ruby:
args = [ ]
ARGV.each do |a|
    if a[0,2] == "--"
        key = a[2..-1].split "="
        if $prefs.has_key? key[0]
            $prefs[key[0]] = (key[1] or true) #Sets option to true if no value given
        else
            $stderr.puts "Error: No option '#{key[0]}'"
        end
    else
        args.push a
    end
end

To use it, make a hash called $prefs holding the default values for all your preferences. When the program is run, it goes through each argument and if it starts with "--" then it checks if that key is in prefs, if it is it changes the value with the part after = (or true if they give nothing after), or else it dies telling the user that that is an invalid option. If it doesn't start with "--", it is pushed onto args. args now contains all your unnamed arguments, and prefs the named ones.

Author:  wtd [ Sat Jun 06, 2009 11:42 pm ]
Post subject:  RE:Quick Argument Parsing

Ruby:
args = [ ]
ARGV.each do |a|
    if a[0,2] == "--"
        key, value = a[2..-1].split "="
        if $prefs.has_key? key
            $prefs[key[0]] = (value or true) #Sets option to true if no value given
        else
            $stderr.puts "Error: No option '#{key}'"
        end
    else
        args.push a
    end
end


: