Class: Hash::Chain

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*hashes) ⇒ Chain

Instance Methods =====================================================



12
13
14
# File 'lib/hash_chain.rb', line 12

def initialize(*hashes)
  @hashes = hashes.flatten
end

Class Method Details

.[](*hashes) ⇒ Object

Class Methods ========================================================



6
7
8
# File 'lib/hash_chain.rb', line 6

def self.[](*hashes)
  new(*hashes)
end

Instance Method Details

#[](key) ⇒ Object



16
17
18
19
20
21
22
23
24
# File 'lib/hash_chain.rb', line 16

def [](key)
  @hashes.each do |hash|
    if (hash.key?(key) or !hash[key].nil?)
      return hash[key]
    end
  end
  
  nil
end

#eachObject



46
47
48
49
50
# File 'lib/hash_chain.rb', line 46

def each
  self.keys.each do |key|
    yield(key, self[key])
  end
end

#empty?Boolean

Returns:

  • (Boolean)


38
39
40
# File 'lib/hash_chain.rb', line 38

def empty?
  !@hashes.find { |hash| !hash.empty? }
end

#key?(key) ⇒ Boolean

Returns:

  • (Boolean)


34
35
36
# File 'lib/hash_chain.rb', line 34

def key?(key)
  !!@hashes.find { |hash| hash.key?(key) }
end

#keysObject



26
27
28
# File 'lib/hash_chain.rb', line 26

def keys
  @hashes.inject([ ]) { |a, h| a += h.keys }.uniq
end

#lengthObject



42
43
44
# File 'lib/hash_chain.rb', line 42

def length
  self.keys.length
end

#to_aObject



66
67
68
# File 'lib/hash_chain.rb', line 66

def to_a
  self.to_h.to_a
end

#to_hObject



52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/hash_chain.rb', line 52

def to_h
  combined = { }
  
  @hashes.each do |hash|
    hash.each do |key, value|
      next if (combined.key?(key))

      combined[key] = value
    end
  end
  
  combined
end

#valuesObject



30
31
32
# File 'lib/hash_chain.rb', line 30

def values
  self.to_h.values
end