Consider this Ruby code snippet:
person = { name: "Alice", age: 30 }
puts person[:name]What will be printed?
person = { name: "Alice", age: 30 }
puts person[:name]Look at how the key is accessed using a symbol.
The hash stores keys and values. Accessing with [:name] returns the value "Alice".
Why do Ruby programmers often use hashes to pass arguments to methods?
Think about how named arguments help readability and flexibility.
Hashes let you pass named arguments, so the order doesn't matter and code is easier to read and maintain.
What error will this Ruby code produce?
options = { color: "red", size: "medium" }
puts options["color"]options = { color: "red", size: "medium" }
puts options["color"]Check the difference between symbol keys and string keys in hashes.
The hash keys are symbols (:color), but the code tries to access with a string key ("color"), which returns nil.
Given this Ruby code:
profile = { user: { name: "Bob", details: { age: 25, city: "NY" } } }
puts profile[:user][:details][:city]What will it print?
profile = { user: { name: "Bob", details: { age: 25, city: "NY" } } }
puts profile[:user][:details][:city]Follow the keys step by step inside the nested hash.
Accessing nested hashes by keys returns the value "NY" for the city.
Why does Ruby use hashes extensively inside its core and libraries?
Think about speed and flexibility when storing data with keys.
Hashes allow quick access to values by keys and can store diverse data, making them ideal for many internal uses.