-
Notifications
You must be signed in to change notification settings - Fork 36
Option Types
Jason Frey edited this page Aug 24, 2018
·
2 revisions
Many built-in option types are available. These types can either be specified by the class-name or a symbol.
-
:flag
,:bool
,:boolean
,TrueClass
,FalseClass
: a boolean option (also referred to as a "flag"). Value is eithertrue
orfalse
-
:int
,:integer
,Integer
: an option that returns an Integer -
:float
,:double
,Float
: an option that returns a Float -
:string
,String
: an option that returns a String -
:io
,IO
: an option that returns an opened IO object (typically a file or a URL) -
:date
,Date
: an option that returns a Date object
Furthermore, Optimist accepts pluralized symbol versions of the above arguments, e.g:
:ints
, :integers
, :floats
, :doubles
, :strings
, :ios
, :dates
These plural versions will return an Array of that object type.
Type checking and type conversion is performed on the option as it is given. Invalid input will cause an error.
opts = Optimist::options do
opt :xx, "x opt", :type => :string
opt :yy, "y opt", :type => :float
opt :zz, "z opt", :type => :integer
end
$ ./types.rb -y ABC
Error: option '-y' needs a floating-point number.
$ ./types.rb -z 4.0
Error: option '-z' needs an integer.
opts = Optimist::options do
opt :xx, "x opt", :type => :string
opt :yy, "y opt", :type => :float
opt :zz, "z opt", :type => :integer
end
p opts
puts "xx class is #{opts[:xx].class}"
puts "yy class is #{opts[:yy].class}"
puts "zz class is #{opts[:zz].class}"
The same option given on the command-line (e.g.: '4'), is converted into different types depending on the :type
.
$ ./types.rb -x 4 -y 4 -z 4
{:xx=>"4", :yy=>4.0, :zz=>4, :help=>false, :xx_given=>true, :yy_given=>true, :zz_given=>true}
xx class is String
yy class is Float
zz class is Fixnum
At this time, there is no way to define custom types. The best known method is to use a :string
type and convert the type after the fact.