Create a Hash: Difference between revisions

From Rosetta Code
Content added Content deleted
No edit summary
 
m (fix redirect)
 
(20 intermediate revisions by 12 users not shown)
Line 1: Line 1:
#REDIRECT [[Associative array/Creation]]
{{task}}

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'

Latest revision as of 19:09, 9 March 2013