Class: Kodekopelli::FrozenKeyHash

Inherits:
Hash
  • Object
show all
Defined in:
lib/kodekopelli/frozen_key_hash.rb

Overview

A FrozenKeyHash differs from a normal Hash in that, once a value has been set for a particular key, subsequent attempts to assign values to the same key will be ignored.

Please note that it is still possible to replace existing keyed values by first calling delete on the relevant key and then adding the new value.

Instance Method Summary collapse

Constructor Details

#initializeFrozenKeyHash

Returns a new, empty hash.

:call-seq:
  FrozenKeyHash.new -> frozen value hash


15
16
17
# File 'lib/kodekopelli/frozen_key_hash.rb', line 15

def initialize
  super
end

Instance Method Details

#[]=(key, value) ⇒ Object

Element Assignment—Associates the value given by a value object with the key given by a key object, unless an object with the same key is already stored in the hash. In the event that an object is already stored in the hash using the key provided, the hash will not be altered.

:call-seq:
  h[ aKeyObject ] = aValueObject -> aValueObject


29
30
31
# File 'lib/kodekopelli/frozen_key_hash.rb', line 29

def []=(key,value)
  self.store(key,value)
end

#store(key, value) ⇒ Object

Synonym for element assignment.

:call-seq:
  h.store( aKeyObject, aValueObject ) -> aValueObject


38
39
40
41
42
# File 'lib/kodekopelli/frozen_key_hash.rb', line 38

def store(key,value)
  unless  has_key?(key)
    super(key,value)
  end
end

#store_all(any_hash) ⇒ Object

Convenience method to merge all entries from another hash into the current instance, while still preserving existing key immutability



49
50
51
52
53
# File 'lib/kodekopelli/frozen_key_hash.rb', line 49

def store_all(any_hash)
  any_hash.each_pair { |key,value|
    self.store(key,value)
  }
end

#to_sObject



55
56
57
58
59
60
61
62
63
64
# File 'lib/kodekopelli/frozen_key_hash.rb', line 55

def to_s
  human_readable = ''
  human_readable += sprintf("%-30s     %s", "<KEY>", "<VALUE>")
  human_readable += "\n"
  each_pair {|key,value|
    human_readable += sprintf("%-30s => %s", key, value)
    human_readable += "\n"
  }
  human_readable
end