Associative array/Creation: Difference between revisions

Content added Content deleted
(Added Scala example)
(Remove double entry for Ruby)
Line 232: Line 232:
==[[Ruby]]==
==[[Ruby]]==
[[Category:Ruby]]
[[Category:Ruby]]
#a hash object that returns nil for unknown keys
A hash object that returns [[nil]] for unknown keys
hash={}
hash={}
hash[666]='devil'
hash[666]='devil'
Line 238: Line 238:
hash[666] # => 'devil'
hash[666] # => 'devil'


#a hash object that returns 'unknown key' for unknown keys
A hash object that returns 'unknown key' for unknown keys
hash=Hash.new('unknown key')
hash=Hash.new('unknown key')
hash[666]='devil'
hash[666]='devil'
Line 244: Line 244:
hash[666] # => 'devil'
hash[666] # => 'devil'


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



===Iterate over key/value===
===Iterate over key/value===
Line 355: Line 354:


Create a generic mapping function that applys a callback to elements in a list:
Create a generic mapping function that applys a callback to elements in a list:

==[[Ruby]]==
[[Category: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'


==[[Smalltalk]]==
==[[Smalltalk]]==