Create a Hash

From Rosetta Code
Revision as of 20:29, 22 January 2007 by rosettacode>Gfannes
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Task
Create a Hash
You are encouraged to solve this task according to the task description, using any language you may know.

Create a Hash object that links keys to values and returns a pre-specified element when a key is unknown.

Ruby

 #a hash object that returns nil for unknown keys
 hash={}
 hash[666]='devil'
 hash[777]  # => nil
 hash[666]  # => 'devil'
 #a hash object that returns 'unknown key' for unknown keys
 hash=Hash.new('unknown key')
 hash[666]='devil'
 hash[777]  # => 'unknown key'
 hash[666]  # => 'devil'
 #a hash object that returns "unknown key #{key}" for unknown keys
 hash=Hash.new{|h,k|h[k]="unknown key #{k}"}
 hash[666]='devil'
 hash[777]  # => 'unknown key 777'
 hash[666]  # => 'devil'