Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Quick Argument Parsing
Index -> Programming, Ruby -> Ruby Submissions
View previous topic Printable versionDownload TopicRate TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
DtY




PostPosted: 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.
Sponsor
Sponsor
Sponsor
sponsor
wtd




PostPosted: 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
Display posts from previous:   
   Index -> Programming, Ruby -> Ruby Submissions
View previous topic Tell A FriendPrintable versionDownload TopicRate TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 2 Posts ]
Jump to:   


Style:  
Search: