Skip to content

Basic Example

Jason Frey edited this page Aug 24, 2018 · 2 revisions

Optimist Example Documentation:

A basic example

require 'optimist'
  opts = Optimist::options do
    opt :monkey, "Use monkey mode"                    # flag --monkey, default false
    opt :name, "Monkey name", :type => :string        # string --name <s>, default nil
    opt :num_limbs, "Number of limbs", :default => 4  # integer --num-limbs <i>, default to 4
  end

  p opts # a hash: { :monkey=>false, :name=>nil, :num_limbs=>4, :help=>false }
  • Optimist::options returns a hash of values. That's all the output you get.
  • opt is used to define an option. The first argument is a symbol which names the option. The second argument is the doc-string. Other arguments are used to denote type, defaults, etc.
  • Underscores in an option-name are converted to dashes. opt :hello_there corresponds to the command-line option --hello-there.
  • All options are inferred to be boolean flags, defaulting to false, unless you specify a default or a type. If given a default, Optimist can infer the type using the default value, so no need to specify both.
  • Short (one-character) option names are created automatically. You can set them manually with :short.

Also, your help command-line options (-h, --help) and help message are created automatically. For the above example, the generated help message is:

$ ./a_basic_example.rb -h
Options:
  -m, --monkey           Use monkey mode
  -n, --name=<s>         Monkey name
  -u, --num-limbs=<i>    Number of limbs (default: 4)
  -h, --help             Show this message
Clone this wiki locally