Hashes and Symbols Flashcards

You may prefer our related Brainscape-certified flashcards:
1
Q

what are hashes?

A

hashes are collections of key-value pairs

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

What happens when you try to access a key that doesn’t exist?

A

You will get the value nil

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

What does nil mean?

A

nil is Ruby’s way of saying “nothing at all.”

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

How do you set a new default value in a hash?

A

my_hash = Hash.new(“Trady Blix”)

Now if you try to access a nonexistent key in my_hash, you’ll get “Trady Blix” as a result.

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

What are symbols?

A

Symbols are not strings and can only be used once. They are used for referencing method names and as hash keys.

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

How do you write a symbol?

A

You write it:

:symbol_name

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

Why are symbols good as hash keys?

A
  1. They cant be changed once they are created (immutable)
  2. Only one symbol with the same name can exist so they save memory
  3. Symbols are faster.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How do you convert between strings and symbols?

A

with
.to_s (symbol to string)
.to_sym (string to symbol)
.intern (string to symbol)

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

How do you assign symbols as keys to a value?

A

You use the new syntax instead of the old hash syntax

new_hash = { 
  one: 1,
  two: 2,
  three: 3
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How can we filter values from a hash?

A

We use the .select method

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

How do we iterate over just a value?

A

With the .each_value method

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

How to we iterate over just a key?

A

With the .each_key method

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