Over a million developers have joined DZone.

Optparse (script) Template

DZone's Guide to

Optparse (script) Template

Free Resource

require 'optparse'

# default options
  :first       => "default value",
  :another     => 23,
  :bool        => false,
  :list        => ["x", "y", "z"],
  :dest        => File.expand_path(File.dirname($0))

ARGV.options do |o|
  script_name = File.basename($0)
  o.set_summary_indent('  ')
  o.banner =    "Usage: #{script_name} [OPTIONS]"
  o.define_head "Abstract description of script"
  o.separator   ""
  o.separator   "Mandatory arguments to long options are mandatory for " +
                "short options too."
  o.on("-f", "--first=[val]", String,
       "A long and short (optional) string argument",
       "Default: #{OPTIONS[:first]}")   { |OPTIONS[:first]| }
  o.on("-a", "--another=val", Integer,
       "Requires an int argument")      { |OPTIONS[:another]| }
  o.on("-b", "--boolean",
       "A boolean argument")            { |OPTIONS[:bool]| }
  o.on("--list=[x,y,z]", Array, 
       "Example 'list' of arguments")   { |OPTIONS[:list]| }
  o.separator ""

  o.on_tail("-h", "--help", "Show this help message.") { puts o; exit }

puts "first:     #{OPTIONS[:first]}"
puts "another:   #{OPTIONS[:another]}"
puts "bool:      #{OPTIONS[:bool]}"
puts "list:      #{OPTIONS[:list].join(',')}"
puts "arguments: #{ARGV}"


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}