Skip to content

Instantly share code, notes, and snippets.

@svenfuchs
Forked from rtomayko/optparse-template.rb
Created May 24, 2019 21:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save svenfuchs/da9fb452ad2991f4b01002d896b7c2b0 to your computer and use it in GitHub Desktop.
Save svenfuchs/da9fb452ad2991f4b01002d896b7c2b0 to your computer and use it in GitHub Desktop.
Ruby optparse template
#!/usr/bin/env ruby
#/ Usage: <progname> [options]...
#/ How does this script make my life easier?
# ** Tip: use #/ lines to define the --help usage message.
$stderr.sync = true
require 'optparse'
# default options
flag = false
option = "default value"
integer = 23
list = ["x", "y", "z"]
# parse arguments
file = __FILE__
ARGV.options do |opts|
opts.on("-f", "--flag") { flag = true }
opts.on("-o", "--opt=val", String) { |val| option = val }
opts.on("-i", "--int=val", Integer) { |val| integer = val }
opts.on("--list=[x,y,z]", Array) { |val| list = val }
opts.on_tail("-h", "--help") { exec "grep ^#/<'#{file}'|cut -c4-" }
opts.parse!
end
# do your thing
warn "ARGV: #{ARGV.inspect}"
warn "flag: #{flag.inspect}"
warn "option: #{option.inspect}"
warn "integer: #{integer.inspect}"
warn "list: #{list.join(',')}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment