Menu
Coddy logo textTech

Recap - Product Hash

Part of the Fundamentals section of Coddy's Ruby journey — lesson 77 of 88.

challenge icon

Challenge

Easy

Read four lines of input:

  1. A product name (string)
  2. An initial price (float)
  3. A new price to update (float)
  4. 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:

  1. Print the product name by accessing the "name" key
  2. Update the "price" key with the new price value
  3. Add a new key "quantity" with the quantity value (as an integer)
  4. Check if the key "quantity" exists and print the result (true or false)
  5. Print the total number of key-value pairs in the hash
  6. 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 hash

All lessons in Fundamentals