Recall & Review
beginner
How do you access the value of a hash by its key in Ruby?
You use the key inside square brackets after the hash name, like
hash[key]. This returns the value stored for that key.Click to reveal answer
beginner
How do you set or change a value in a Ruby hash?
Assign a new value to a key using
hash[key] = value. If the key exists, it updates the value; if not, it adds a new key-value pair.Click to reveal answer
beginner
What happens if you try to access a key that does not exist in a Ruby hash?
Ruby returns
nil if the key is not found in the hash.Click to reveal answer
intermediate
How can you safely access nested hash values without errors?
You can use the safe navigation operator
&. or check if keys exist before accessing nested values to avoid errors.Click to reveal answer
intermediate
What is the difference between accessing values with
hash[key] and hash.fetch(key)?hash[key] returns nil if the key is missing, while hash.fetch(key) raises an error unless you provide a default value.Click to reveal answer
How do you get the value for the key :name from a hash called person?
✗ Incorrect
In Ruby, you access hash values using square brackets with the key, like
person[:name].What does Ruby return if you access a hash with a key that does not exist?
✗ Incorrect
Ruby returns
nil when a key is not found in a hash.How do you add or update a key :age with value 30 in a hash called person?
✗ Incorrect
You assign the value directly with
person[:age] = 30 to add or update a key.Which method raises an error if the key is missing in a hash?
✗ Incorrect
hash.fetch(key) raises a KeyError if the key is missing, unlike hash[key] which returns nil.What is a safe way to access nested hash values?
✗ Incorrect
Using the safe navigation operator
&. helps avoid errors when accessing nested hashes.Explain how to access and set values in a Ruby hash with examples.
Think about how you get and change values in a dictionary or map.
You got /3 concepts.
What happens when you try to access a key that does not exist in a Ruby hash? How can you handle this safely?
Consider what Ruby returns by default and how to avoid errors.
You got /4 concepts.