Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
documented/common/class_exts/hash.rb

Overview

Extension to the Hash class This class adds additional methods to the built-in Hash class.

Examples:

Using the extended Hash methods

my_hash = Hash.new
Hash.put(my_hash, "key1.key2", "value")

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.put(target, path, val) ⇒ Hash

Puts a value into a nested hash structure at the specified path.

Examples:

Inserting a value into a nested hash

my_hash = {}
Hash.put(my_hash, "key1.key2", "value")
# my_hash now is { "key1" => { "key2" => "value" } }

Parameters:

  • target (Hash)

    The target hash to modify.

  • path (Array, String)

    The path where the value should be placed.

  • val (Object)

    The value to be inserted at the specified path.

Returns:

  • (Hash)

    The original target hash.

Raises:

  • (ArgumentError)

    If the path is empty.



19
20
21
22
23
24
25
26
# File 'documented/common/class_exts/hash.rb', line 19

def self.put(target, path, val)
  path = [path] unless path.is_a?(Array)
  fail ArgumentError, "path cannot be empty" if path.empty?
  root = target
  path.slice(0..-2).each { |key| target = target[key] ||= {} }
  target[path.last] = val
  root
end

Instance Method Details

#to_structOpenStruct

Converts the hash to an OpenStruct object.

Examples:

Converting a hash to OpenStruct

my_hash = { "name" => "John", "age" => 30 }
struct = my_hash.to_struct
# struct.name returns "John"

Returns:

  • (OpenStruct)

    An OpenStruct representation of the hash.



34
35
36
# File 'documented/common/class_exts/hash.rb', line 34

def to_struct
  OpenStruct.new self
end