Associative array/Creation: Difference between revisions

→‎{{header|Ruby}}: add examples of literals; format code with spaces as conventional
(→‎{{header|Elixir}}: show map literals)
(→‎{{header|Ruby}}: add examples of literals; format code with spaces as conventional)
Line 5,239:
 
=={{header|Ruby}}==
===Hash literals===
A hash object that returns [[nil]] for unknown keys
Ruby has literal syntax for Hash objects.
<syntaxhighlight lang="ruby">hash={}
 
hash[666]='devil'
A Hash with symbols as keys:
<syntaxhighlight lang="ruby">
{:name => 'Zeus', :planet => 'Jupiter'}
</syntaxhighlight>
 
Shorthand for symbol keys:
 
<syntaxhighlight lang="ruby">
{name: 'Zeus', planet: 'Jupiter'}
</syntaxhighlight>
 
A Hash with keys and values of arbitrary types:
 
<syntaxhighlight lang="ruby">
{1 => 'two', three: 4}
</syntaxhighlight>
 
An empty Hash:
 
<syntaxhighlight lang="ruby">
{}
</syntaxhighlight>
 
===Customizing the default value===
 
A hashHash object that returns [[nil]] for unknown keys:
<syntaxhighlight lang="ruby">hash = {}
hash[666] = 'devil'
hash[777] # => nil
hash[666] # => 'devil'</syntaxhighlight>
 
A hashHash object that returns 'unknown key' for unknown keys:
<syntaxhighlight lang="ruby">hash = Hash.new('unknown key')
hash[666] = 'devil'
hash[777] # => 'unknown key'
hash[666] # => 'devil'</syntaxhighlight>
 
A hashHash object that returns "unknown key #{key}" for unknown keys:
<syntaxhighlight lang="ruby">hash = Hash.new { |h, k| "unknown key #{k}" }
hash[666] = 'devil'
hash[777] # => 'unknown key 777'
hash[666] # => 'devil'</syntaxhighlight>
 
A hashHash object that adds "key #{key} was added at #{Time.now}" to the hash the first time an unknown key is seen:
<syntaxhighlight lang="ruby">hash = Hash.new { |h, k| h[k] = "key #{k} was added at #{Time.now}" }
hash[777] # => 'key 777 was added at Sun Apr 03 13:49:57 -0700 2011'
hash[555] # => 'key 555 was added at Sun Apr 03 13:50:01 -0700 2011'
21

edits