Hashes and Symbols Flashcards
what are hashes?
hashes are collections of key-value pairs
What happens when you try to access a key that doesn’t exist?
You will get the value nil
What does nil mean?
nil is Ruby’s way of saying “nothing at all.”
How do you set a new default value in a hash?
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.
What are symbols?
Symbols are not strings and can only be used once. They are used for referencing method names and as hash keys.
How do you write a symbol?
You write it:
:symbol_name
Why are symbols good as hash keys?
- They cant be changed once they are created (immutable)
- Only one symbol with the same name can exist so they save memory
- Symbols are faster.
How do you convert between strings and symbols?
with
.to_s (symbol to string)
.to_sym (string to symbol)
.intern (string to symbol)
How do you assign symbols as keys to a value?
You use the new syntax instead of the old hash syntax
new_hash = { one: 1, two: 2, three: 3 }
How can we filter values from a hash?
We use the .select method
How do we iterate over just a value?
With the .each_value method
How to we iterate over just a key?
With the .each_key method