Accessing Hash Elements
Part of the Fundamentals section of Coddy's Ruby journey — lesson 74 of 88.
Now that you know how to create hashes, you need to retrieve the values stored inside them. Unlike arrays where you use numeric indexes, hashes use keys to access their values.
Place the key inside square brackets to get its corresponding value:
person = {"name" => "Alice", "age" => 25, "city" => "Paris"}
puts person["name"] # Outputs: Alice
puts person["age"] # Outputs: 25The key must match exactly what you used when creating the hash. If you try to access a key that doesn't exist, Ruby returns nil:
person = {"name" => "Alice", "age" => 25}
puts person["country"] # Outputs: (nothing - nil)You can also use the fetch method, which lets you provide a default value when the key is missing:
person = {"name" => "Alice"}
puts person.fetch("name", "Unknown") # Outputs: Alice
puts person.fetch("country", "Unknown") # Outputs: UnknownThis is useful when you want to handle missing keys gracefully instead of getting nil.
Challenge
EasyRead four lines of input:
- A product name (string)
- A price (float)
- A quantity in stock (integer)
- A key to look up (string)
Create a hash called product with the following key-value pairs:
"name"mapped to the product name"price"mapped to the price (as a float)"stock"mapped to the quantity (as an integer)
Then, use the fetch method to retrieve the value for the key provided in the fourth input. If the key doesn't exist, use "Not found" as the default value. Print the result.
For example, if the inputs are Laptop, 999.99, 15, and price, the output should be:
999.99If the inputs are Keyboard, 49.99, 100, and name, the output should be:
KeyboardIf the inputs are Mouse, 29.99, 50, and color, the output should be:
Not foundIf the inputs are Monitor, 299.0, 8, and stock, the output should be:
8Cheat sheet
To access values in a hash, use the key inside square brackets:
person = {"name" => "Alice", "age" => 25, "city" => "Paris"}
puts person["name"] # Outputs: Alice
puts person["age"] # Outputs: 25If a key doesn't exist, Ruby returns nil:
person = {"name" => "Alice", "age" => 25}
puts person["country"] # Outputs: (nothing - nil)Use the fetch method to provide a default value for missing keys:
person = {"name" => "Alice"}
puts person.fetch("name", "Unknown") # Outputs: Alice
puts person.fetch("country", "Unknown") # Outputs: UnknownTry it yourself
# Read input
product_name = gets.chomp
price = gets.chomp.to_f
quantity = gets.chomp.to_i
key_to_lookup = gets.chomp
# TODO: Write your code below
# Create a hash called 'product' with keys "name", "price", and "stock"
# Then use the fetch method to retrieve the value for key_to_lookup
# Use "Not found" as the default value if the key doesn't exist
# Output the result
puts resultThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 42Variables and Data Types
Numbers and VariablesString Data TypeBoolean Data TypeSymbol Data TypeChecking Data TypesNaming ConventionsRecap - Variable Creation8Loops
For Loop with RangesWhile LoopBreakNextRecap - FactorialTimes LoopUntil LoopNested LoopsRecap - Dynamic Input11Arrays
Creating ArraysAccessing Array ElementsModifying ArraysArray MethodsRecap - Product ArrayRecap - Reversed ArrayArray Shortcuts14Hashes
Creating HashesAccessing Hash ElementsModifying HashesHash MethodsRecap - Product HashSymbols as Hash Keys3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators6Basic IO
Output with putsOutput with print and pOutput With VariablesInput with getsChomp MethodType ConversionRecap - Age CalculatorRecap - True or False