Class: Hash

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

Overview

Represents a collection of key-value pairs.

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.put(target, path, val) ⇒ Hash

Adds a value to the hash at the specified path.

Examples:

Add a value to a nested hash

my_hash = {}
Hash.put(my_hash, "a.b.c", 42)
# my_hash now is {"a" => {"b" => {"c" => 42}}}

Parameters:

  • target (Hash)

    the hash to modify

  • path (Array<String>, String)

    the path where the value should be added

  • val (Object)

    the value to add at the specified path

Returns:

  • (Hash)

    the modified hash

Raises:

  • (ArgumentError)

    if path is empty



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

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.

Returns:

  • (OpenStruct)

    an OpenStruct representation of the hash.



29
30
31
# File 'documented/common/class_exts/hash.rb', line 29

def to_struct
  OpenStruct.new self
end