Class: General::GDotHash

Inherits:
Object
  • Object
show all
Defined in:
lib/gdothash.rb

Overview

Created: 9 - 27 - 2016

Instance Method Summary collapse

Constructor Details

#initialize(hash = {}) ⇒ GDotHash

Initializes the given GDotHash with the given hash

Parameter: hash - the hash being manipulated



30
# File 'lib/gdothash.rb', line 30

def initialize(hash={}); @hash = hash; end

Instance Method Details

#[](key) ⇒ Object

Gets the value at the given key

Parameter: key - the key to return

Return: the value at the given key



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/gdothash.rb', line 67

def [] key
  # Split keys

  subkeys = key.to_s.split(".").collect(&:to_sym)

  # Travel down to value

  get = @hash
  subkeys.each do |subkey|
    if get.is_a?(Hash) && get.has_key?(subkey)
      get = get[subkey]
    else
      raise ArgumentError, "key is not defined in hash: #{key}"
    end
  end

  # Return value

  return get
end

#[]=(key, value) ⇒ Object

Sets the given key to the given value

Parameter: key - the key to set Parameter: value - the value to set



89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/gdothash.rb', line 89

def []= key, value
  # Split subkeys

  subkeys = key.to_s.split(".").collect(&:to_sym)

  # Generate structure of new data

  new_data = Hash.new
  sub = new_data
  subkeys[0...-1].each do |subkey|
    sub[subkey] = Hash.new
    sub = sub[subkey]
  end
  sub[subkeys[-1]] = value

  # Merge hash with new data

  @hash.merge! new_data
end

#has_key?(key) ⇒ Boolean

Returns true if the GDotHash contains the given key

Parameter: key - the key to check

Return: true if the GDotHash contains the given key

Returns:

  • (Boolean)


42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/gdothash.rb', line 42

def has_key? key
  # Split keys

  subkeys = key.to_s.split(".").collect(&:to_sym)

  # Check each subkey

  sub = @hash
  subkeys.each do |subkey|
    # Return false if subhash doesn't contain key

    # Else continue

    if sub.is_a?(Hash) && sub.has_key?(subkey)
      sub = sub[subkey]
    else
      return false
    end
  end

  # Return true if passed

  return true
end

#to_sObject

Returns the string representation of the hash

Return: the string representation of the hash



35
# File 'lib/gdothash.rb', line 35

def to_s; @hash.to_s; end