Ruby: Hashes Flashcards
What happens if the hash can’t find the key?
A hash by default returns nil when indexed by a key it doesn’t contain. Normally this is convenient, because nil means false when used in condi- tional expressions. Sometimes you’ll want to change this default.
How do you specify a default value for a hash?
histogram = Hash.new(0) # The default value is zero
Now, let’s look for something it can’t find:
histogram[‘ruby’] # => 0
New Has Syntax
symbols are so frequently used as hash keys that Ruby 1.9 introduces a new syntax— you can use name: value pairs to create a hash if the keys are symbols:
inst_section = {
cello: ‘string’, clarinet: ‘woodwind’, drum: ‘percussion’, oboe: ‘woodwind’, trumpet: ‘brass’, violin: ‘string’