Class: Slop::Options

Inherits:
Array
  • Object
show all
Defined in:
lib/slop/options.rb

Instance Method Summary collapse

Instance Method Details

#[](flag) ⇒ Option

Fetch an Option object. This method overrides Array#[] to provide a nicer interface for fetching options via their short or long flag. The reason we don't use a Hash here is because an option cannot be identified by a single label. Instead this method tests against a short flag first, followed by a long flag. When passing this method an Integer, it will work as an Array usually would, fetching the Slop::Option at this index.

Examples:

opts = Slop.parse { on :v, "Verbose mode" }
opts.options[:v] #=> Option
opts.options[:v].description #=> "Verbose mode"

Parameters:

  • flag (Object)

    The short/long flag representing the option

Returns:

  • (Option)

    the option assoiated with this flag



30
31
32
33
34
35
36
37
38
# File 'lib/slop/options.rb', line 30

def [](flag)
  if flag.is_a? Integer
    super
  else
    find do |option|
      [option.short_flag, option.long_flag].include? flag.to_s
    end
  end
end

#to_hash(symbols) ⇒ Hash

Parameters:

  • symbols (Boolean)

    true to cast hash keys to symbols

Returns:

  • (Hash)

See Also:



7
8
9
10
11
12
13
14
# File 'lib/slop/options.rb', line 7

def to_hash(symbols)
  reduce({}) do |hsh, option|
    key = option.key
    key = key.to_sym if symbols
    hsh[key] = option.argument_value
    hsh
  end
end

#to_helpString

Returns All options in a pretty help string.

Returns:

  • (String)

    All options in a pretty help string

See Also:



42
43
44
45
46
47
# File 'lib/slop/options.rb', line 42

def to_help
  heads = reject(&:tail)
  tails = select(&:tail)
  all = (heads + tails).select(&:help)
  all.map(&:to_s).join("\n")
end