0
0
Rubyprogramming~5 mins

Accessing and setting values in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Aperson.name
Bperson[:name]
Cperson->name
Dperson.get(:name)
What does Ruby return if you access a hash with a key that does not exist?
Anil
B0
CAn error
Dfalse
How do you add or update a key :age with value 30 in a hash called person?
Aperson[:age] = 30
Bperson.add(:age, 30)
Cperson.set(:age, 30)
Dperson.age = 30
Which method raises an error if the key is missing in a hash?
Ahash.get(key)
Bhash[key]
Chash.fetch(key)
Dhash.find(key)
What is a safe way to access nested hash values?
AUse hash.getNested(key1, key2).
BUse dot notation like hash.key.
CUse hash[key][key2] without checks.
DUse safe navigation operator &.
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.