Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/fedux_org_stdlib/core_ext/hash/list.rb,
lib/fedux_org_stdlib/core_ext/hash/options.rb

Overview

Hash

Instance Method Summary collapse

Instance Method Details

#to_list(format: '%s: %s', **args) ⇒ String

Convert Hash to list

For more examples see ‘fedux_org_stdlib/core_ext/array/list’

Examples:

Change separator for key and value


input = {
  opt1: 'asdf',
  opt2: 'asdf'
}

input.to_list(format: "%s | %s")
=> "opt1 | asdf", "opt2 | asdf"

Change separator between key/value-pairs


input = {
  opt1: 'asdf',
  opt2: 'asdf'
}

input.to_list(format: "%s | %s")
=> "opt1 | asdf", "opt2 | asdf"

Change character around key/value-pair


input = {
  opt1: 'asdf',
  opt2: 'asdf'
}

input.to_list(around: "'")
=> 'opt1: asdf', 'opt2: asdf'

Returns:

  • (String)

    A string representation of hash as list



42
43
44
# File 'lib/fedux_org_stdlib/core_ext/hash/list.rb', line 42

def to_list(format: '%s: %s', **args)
  map { |key, value| format(format, key, value) }.to_list(**args)
end

#to_optionsObject

Convert hash to command line options

Examples:

Convert true value


hash = {
  opt1: true
}

hash.to_options
# => [ '--opt1']

Convert false value


hash = {
  opt1: false
}

hash.to_options
# => [ '--no-opt1']

Convert other values


hash = {
  opt1: 'string'
}

hash.to_options
# => [ '--opt1', 'string']

Clean keys


hash = {
  '$opt1' => 'string'
}

hash.to_options
# => [ '--opt1', 'string']

Escape values


hash = {
  'opt1' => '$string'
}

hash.to_options
# => [ '--opt1', '\$string']


53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/fedux_org_stdlib/core_ext/hash/options.rb', line 53

def to_options
  each_with_object([]) do |(key, value), a|
    key = Shellwords.clean(key)

    if value.is_a? TrueClass
      a << "--#{key}"
    elsif value.is_a? FalseClass
      a << "--no-#{key}"
    else
      a << "--#{key}"
      a << Shellwords.escape(value)
    end
  end
end