Menu
Coddy logo textTech

Add Expense

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

challenge icon

Challenge

Easy

Build upon your expense tracker from the previous lesson by adding the "Add Expense" functionality.

Your program should:

  1. Initialize an empty array called expenses
  2. Create a loop do that displays the menu and reads user input
  3. When the user enters "1", prompt for the expense name and amount, create a hash with :name and :amount keys, add it to the expenses array, and print Expense added!
  4. When the user enters "5", print Goodbye! and exit the loop

The menu should display exactly as before:


--- Expense Tracker ---
1. Add Expense
2. View Expenses
3. Total & Average
4. Clear All
5. Exit
Choose an option: 

When option "1" is selected, display these prompts:

Expense name: 

Then after reading the name:

Amount: 

Use print for all prompts (so the cursor stays on the same line). Convert the amount to a float using to_f.

The program will receive multiple inputs in sequence: the menu choice, and if choice is "1", the expense name and amount will follow.

For example, if the inputs are 1, Coffee, 4.50, then 5, the output should be:


--- Expense Tracker ---
1. Add Expense
2. View Expenses
3. Total & Average
4. Clear All
5. Exit
Choose an option: Expense name: Amount: Expense added!

--- Expense Tracker ---
1. Add Expense
2. View Expenses
3. Total & Average
4. Clear All
5. Exit
Choose an option: Goodbye!

If the inputs are 1, Lunch, 12.99, 1, Bus fare, 2.50, then 5, the output should be:


--- Expense Tracker ---
1. Add Expense
2. View Expenses
3. Total & Average
4. Clear All
5. Exit
Choose an option: Expense name: Amount: Expense added!

--- Expense Tracker ---
1. Add Expense
2. View Expenses
3. Total & Average
4. Clear All
5. Exit
Choose an option: Expense name: Amount: Expense added!

--- Expense Tracker ---
1. Add Expense
2. View Expenses
3. Total & Average
4. Clear All
5. Exit
Choose an option: Goodbye!

Try it yourself

expenses = []

loop do
  puts "\n--- Expense Tracker ---"
  puts "1. Add Expense"
  puts "2. View Expenses"
  puts "3. Total & Average"
  puts "4. Clear All"
  puts "5. Exit"
  print "Choose an option: "
  
  choice = gets.chomp
  
  if choice == "5"
    puts "Goodbye!"
    break
  end
end

All lessons in Fundamentals