Class: Aduki::RecursiveHash

Inherits:
Hash
  • Object
show all
Defined in:
lib/aduki/recursive_hash.rb

Instance Method Summary collapse

Methods inherited from Hash

#recursively_delete_keys!, #recursively_remove_by_value!, #recursively_replace_keys!, #recursively_replace_values, #recursively_stringify_keys!

Instance Method Details

#[]=(key, value) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/aduki/recursive_hash.rb', line 4

def []= key, value
  return super(key, value) unless key.is_a? String

  k0, k1 = key.split(/\./, 2)

  if k0.match(/\[\d+\]$/)
    getter = k0.gsub(/\[\d+\]$/, '')
    index  = k0.gsub(/.*\[(\d+)\]$/, '\1').to_i
    subarray = self[getter] || []
    if k1
      subarray[index] ||= Aduki::RecursiveHash.new
      subarray[index][k1] = value
    else
      subarray[index] = value
    end
    super getter, subarray
  else
    return super(key, value) if k1.nil?
    existing = self[k0]
    subhash = (existing.is_a? Hash) ? existing : Aduki::RecursiveHash.new
    subhash[k1] = value
    super k0, subhash
  end
end

#copy(other) ⇒ Object



29
30
31
32
# File 'lib/aduki/recursive_hash.rb', line 29

def copy other
  other.each { |k, v| self[k]= v }
  self
end