Created
July 10, 2015 11:01
-
-
Save mig-hub/42f58443f4f4e70382b2 to your computer and use it in GitHub Desktop.
Parse only options from the command line in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Here is a simple trick if you have a command line which | |
# needs to accept options on the command line of the form: | |
# $ mycommand domain=github.com ssl=true | |
defaults = { | |
domain: 'www.example.com', | |
port: 80, | |
ssl: false | |
} | |
o = defaults.merge( | |
Hash[ | |
ARGV.map do |a| | |
k,v = a.split('=') | |
if v=='true' | |
v = true | |
elsif v=='false' | |
v = false | |
elsif v=~/^\d+$/ | |
v = v.to_i | |
end | |
[k.to_sym,v] | |
end | |
] | |
) | |
# The typecasting could be improved but the idea is here. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment