Ruby: Hashes Flashcards

1
Q

What happens if the hash can’t find the key?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How do you specify a default value for a hash?

A

histogram = Hash.new(0) # The default value is zero

Now, let’s look for something it can’t find:

histogram[‘ruby’] # => 0

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

New Has Syntax

A

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’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly