Skip to content

Accessing Values

mosop edited this page Jan 22, 2017 · 38 revisions

Accessing Named Values

To access named values, use value accessors or value hashes.

Value Accessors

If you define a named value, a corresponding value accessor is automatically defined.

A value accessor name is determined by a value name. Any leading minus signs (-) are eliminated and other minus signs are converted to underscore letters (_). For example, --option-name is converted to option_name.

If a value type is Bool, the corresponding accessor name has a trailing ? mark.

class Model < Optarg::Model
  string "-s"
  bool "-b"
  array "-a"
  arg "arg"
  arg_array "args"
end

result = Model.parse(%w(-s foo -b -a bar -a baz blep blah boop))
result.s # "foo"
result.b? # true
result.a # ["bar", "baz"]
result.arg # "blep"
result.args # ["blah", "boop"]

If a value type is Bool and the value is undefined, the corresponding value accessor returns false.

If a value type is String, a nilable accessor is also defined. The nilable accessor returns nil if the value is undefined.

class Model < Optarg::Model
  string "-s"
  bool "-b"
end

result = Model.parse(%w())
result.s # raises an error
result.s? # nil
result.b? # false

If a value has multiple names, multiple accessor is defined.

class Model < Optarg::Model
  bool %w(-f --force)
end

result = Model.parse(%w(--force))
result.f? # true
result.force? # true

Value Hashes

A value hash is a Hash object that each model instance creates for storing parsed values.

To access hash objects, use the model instance's [] method with a value class.

class Model < Optarg::Model
  string "-s1"
  string "-s2"
  bool "-b1"
  bool "-b2"
  array "-a1"
  array "-a2"
  arg "arg1"
  arg "arg2"
  arg_array "args"
end

result = Model.parse(%w(-s1 a -s2 b -b1 -b2 -a1 c -a1 d -a2 e -a2 f g h i j))
result[String] # {"-s1" => "a", "-s2" => "b", "arg1" => "g", "arg2" => "h"}
result[Bool] # {"-b1" => true, "-b2" => true}
result[Array(String)] # {"-a1" => ["c", "d"], "-a2" => ["e", "f"], "args" => ["i", "j"]}

If a value has multiple names, only the first name can be used as a hash key.

class Model < Optarg::Model
  bool %w(-f --force)
end

result = Model.parse(%w(--force))
result[Bool]["-f"] # true
result[Bool]["--force"] # raises an error
Clone this wiki locally