Quick Argument Parsing
Author |
Message |
DtY
![](http://compsci.ca/v3/uploads/user_avatars/8576159234be48b7a8b0e8.png)
|
Posted: 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. |
|
|
|
|
![](images/spacer.gif) |
Sponsor Sponsor
![Sponsor Sponsor](templates/subSilver/images/ranks/stars_rank5.gif)
|
|
![](images/spacer.gif) |
wtd
|
Posted: 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 |
|
|
|
|
|
![](images/spacer.gif) |
|
|