Recap - Product Hash
Part of the Fundamentals section of Coddy's Ruby journey — lesson 77 of 88.
Challenge
EasyRead four lines of input:
- A product name (string)
- An initial price (float)
- A new price to update (float)
- A quantity to add as a new key-value pair (integer)
Create a hash called product with the following initial key-value pairs:
"name"mapped to the product name"price"mapped to the initial price (as a float)
Then perform these operations in order:
- Print the product name by accessing the
"name"key - Update the
"price"key with the new price value - Add a new key
"quantity"with the quantity value (as an integer) - Check if the key
"quantity"exists and print the result (trueorfalse) - Print the total number of key-value pairs in the hash
- Print the final hash
For example, if the inputs are Laptop, 999.99, 899.99, and 50, the output should be:
Laptop
true
3
{"name"=>"Laptop", "price"=>899.99, "quantity"=>50}If the inputs are Keyboard, 75.0, 59.99, and 100, the output should be:
Keyboard
true
3
{"name"=>"Keyboard", "price"=>59.99, "quantity"=>100}If the inputs are Mouse, 29.99, 24.99, and 200, the output should be:
Mouse
true
3
{"name"=>"Mouse", "price"=>24.99, "quantity"=>200}Try it yourself
# Read input
product_name = gets.chomp
initial_price = gets.chomp.to_f
new_price = gets.chomp.to_f
quantity = gets.chomp.to_i
# TODO: Write your code below
# 1. Create a hash called 'product' with "name" and "price" keys
# 2. Print the product name by accessing the "name" key
# 3. Update the "price" key with the new price
# 4. Add a new key "quantity" with the quantity value
# 5. Check if "quantity" key exists and print the result
# 6. Print the total number of key-value pairs
# 7. Print the final hashAll 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