Skip to content

Instantly share code, notes, and snippets.

@mig-hub
Created July 10, 2015 11:01
Show Gist options
  • Save mig-hub/42f58443f4f4e70382b2 to your computer and use it in GitHub Desktop.
Save mig-hub/42f58443f4f4e70382b2 to your computer and use it in GitHub Desktop.
Parse only options from the command line in Ruby
# 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