Class: Hash

Inherits:
Object show all
Defined in:
lib/golly-utils/ruby_ext/options.rb,
lib/golly-utils/ruby_ext/deep_dup.rb,
lib/golly-utils/ruby_ext/hash_combinations.rb

Instance Method Summary collapse

Instance Method Details

#deep_dupObject

Creates a copy of the hash with deep copies of each key and value.

See Also:



22
23
24
25
26
27
28
# File 'lib/golly-utils/ruby_ext/deep_dup.rb', line 22

def deep_dup
  duplicate = {}
  each_pair do |k,v|
    duplicate[k.deep_dup]= v.deep_dup
  end
  duplicate
end

#validate_keys(valid_keys, error_msg = "Invalid hash keys") ⇒ self

Checks that all keys in this hash are part of a specific set; fails if not.

Parameters:

  • valid_keys (Array)

    A set of valid keys.

  • error_msg (String) (defaults to: "Invalid hash keys")

    A message to include in the error when raised.

Returns:

  • (self)

Raises:

  • Invalid keys are present.



9
10
11
12
13
14
15
# File 'lib/golly-utils/ruby_ext/options.rb', line 9

def validate_keys(valid_keys, error_msg = "Invalid hash keys")
  invalid= self.keys - [valid_keys].flatten
  unless invalid.empty?
    raise "#{error_msg}: #{invalid.sort_by(&:to_s).map(&:inspect).join ', '}"
  end
  self
end

#validate_option_keys(*valid_keys) ⇒ self

Checks that all keys in this hash are part of a specific set; fails if not.

Differs from #validate_keys by providing an option-related error message.

Parameters:

  • valid_keys

    A set of valid keys.

Returns:

  • (self)

Raises:

  • Invalid keys are present.



24
25
26
# File 'lib/golly-utils/ruby_ext/options.rb', line 24

def validate_option_keys(*valid_keys)
  validate_keys valid_keys, "Invalid options provided"
end

#value_combinationsArray<Hash>

Given a hash where each value can be a single value or an array of potential values, this generate a hash for each combination of values across all keys.

Examples:

# Here key :a has 3 possible values, :b has 2, and :c and :d have only 1 each.
x = {a:%w[x y z], b:[1,2], c:'true', d:nil}

x.value_combinations
# will return:

[
 {a:'x', b:1, c:'true', d:nil},
 {a:'y', b:1, c:'true', d:nil},
 {a:'z', b:1, c:'true', d:nil},
 {a:'x', b:2, c:'true', d:nil},
 {a:'y', b:2, c:'true', d:nil},
 {a:'z', b:2, c:'true', d:nil},
]

Returns:



23
24
25
# File 'lib/golly-utils/ruby_ext/hash_combinations.rb', line 23

def value_combinations
  collect_value_combinations [], {}, keys
end