Class: StaticHash

Inherits:
Hash show all
Defined in:
lib/carat/statichash.rb

Overview

StaticHash

A Hash object which raises an error if any previously-defined key attempts to be set again.

Synopsis

foo = StaticHash.new
foo['name'] = 'Tom'    #=> 'Tom'
foo['age']  = 30       #=> 30
foo['name'] = 'Bob'

produces

Error: StaticHash has value for key 'name' in object:
    {"name"=>"Tom", "age"=>30} (RuntimeError)

Author(s)

  • Gavin Kistner

    1. Onoma

Adapted from Gavin Kistner’s WriteOnceHash in basiclibrary.rb Copyright ©2004 Gavin Kistner

It is covered under the license viewable at phrogz.net/JS/_ReuseLicense.txt Reuse or modification is free provided you abide by the terms of that license. (Including the first two lines above in your source code usually satisfies the conditions.)

History

  • 2005.04.11 Passed basic test.

Instance Method Summary collapse

Instance Method Details

#[]=(key, val) ⇒ Object

Set a value for a key; raises an error if that key already exists with a different value.



42
43
44
45
46
47
# File 'lib/carat/statichash.rb', line 42

def []=(key,val)
  if self.has_key?(key) && self[key]!=val
    raise ArgumentError, "StaticHash already has value for key '#{key.to_s}'"
  end
  super
end