Modifying Hashes
Part of the Fundamentals section of Coddy's Ruby journey — lesson 75 of 88.
Hashes aren't static once created. You can add new key-value pairs, update existing values, and remove entries as your program runs.
To add a new pair or update an existing value, assign to the key using square brackets:
person = {"name" => "Alice", "age" => 25}
person["city"] = "Paris" # Adds a new key-value pair
person["age"] = 26 # Updates existing value
puts person # Outputs: {"name"=>"Alice", "age"=>26, "city"=>"Paris"}If the key exists, the value gets replaced. If it doesn't exist, a new pair is added to the hash.
To remove a key-value pair, use the delete method with the key you want to remove:
person = {"name" => "Alice", "age" => 25, "city" => "Paris"}
person.delete("city")
puts person # Outputs: {"name"=>"Alice", "age"=>25}The delete method returns the value that was removed, which can be useful if you need to use it:
person = {"name" => "Alice", "age" => 25}
removed_age = person.delete("age")
puts removed_age # Outputs: 25If you try to delete a key that doesn't exist, Ruby simply returns nil without raising an error.
Challenge
EasyRead four lines of input:
- A student name (string)
- An initial grade (integer)
- A new grade to update (integer)
- A new key-value pair in the format
key:value(e.g.,subject:Math)
Create a hash called student with the following initial key-value pairs:
"name"mapped to the student name"grade"mapped to the initial grade (as an integer)
Then perform these modifications:
- Update the
"grade"key with the new grade value - Add a new key-value pair using the key and value from the fourth input (the value should remain a string)
- Delete the
"name"key from the hash and store the removed value
Print the removed name on the first line, then print the final hash on the second line.
For example, if the inputs are Alice, 85, 92, and subject:Math, the output should be:
Alice
{"grade"=>92, "subject"=>"Math"}If the inputs are Bob, 70, 75, and status:passing, the output should be:
Bob
{"grade"=>75, "status"=>"passing"}If the inputs are Charlie, 100, 95, and note:excellent, the output should be:
Charlie
{"grade"=>95, "note"=>"excellent"}Cheat sheet
To add a new key-value pair or update an existing value in a hash, use square brackets:
person = {"name" => "Alice", "age" => 25}
person["city"] = "Paris" # Adds a new key-value pair
person["age"] = 26 # Updates existing value
puts person # Outputs: {"name"=>"Alice", "age"=>26, "city"=>"Paris"}If the key exists, the value gets replaced. If it doesn't exist, a new pair is added.
To remove a key-value pair, use the delete method:
person = {"name" => "Alice", "age" => 25, "city" => "Paris"}
person.delete("city")
puts person # Outputs: {"name"=>"Alice", "age"=>25}The delete method returns the removed value:
removed_age = person.delete("age")
puts removed_age # Outputs: 25If you try to delete a key that doesn't exist, Ruby returns nil without raising an error.
Try it yourself
# Read input
name = gets.chomp
initial_grade = gets.to_i
new_grade = gets.to_i
key_value_pair = gets.chomp
# TODO: Write your code below
# 1. Create a hash called 'student' with "name" and "grade" keys
# 2. Update the "grade" key with the new grade value
# 3. Parse the key_value_pair and add it to the hash
# 4. Delete the "name" key and store the removed value
# Output the removed name
puts removed_name
# Output the final hash
puts studentThis 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