Hashes (Key-Value Mappings)
Hashes store data in key-value pairs. In modern Ruby, symbols are preferred as keys to optimize memory efficiency.
1 Rocket Syntax vs. Symbol Key Shorthands
Ruby hashes support two key syntaxes:
- Rocket Syntax (`=>`): Traditional syntax. Can use any object type as keys: `:name => "Bob"`.
- Symbol Shorthand Syntax: Modern syntax. Syntactically cleaner and automatically processes keys as symbols: `name: "Bob"`.
2 Hash Operations Code
Let's run a program declaring hashes, accessing values, and deleting keys:
Ruby — Hashes
▶ Run Code
# Modern Symbol key shorthand syntax
student = {
name: "Alice",
age: 21,
gpa: 3.8
}
puts "Student Name: #{student[:name]}" # Accessed using symbol
puts "Keys in Hash: #{student.keys}"
# Fetch with default fallback
rating = student.fetch(:rating, "No Rating Available")
puts "Rating: #{rating}"
# Delete key
student.delete(:age)
puts "Updated Hash: #{student.inspect}"
3 Code Challenge
Challenge: Write a program that stores product items and prices in a hash. Write a loop to iterate through the hash, printing each product name and its price.