Menu
Coddy logo textTech

Total And Average

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

challenge icon

Challenge

Easy

Build upon your expense tracker by adding the "Total & Average" 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 "2", display all expenses or a message if none exist
  5. When the user enters "3", calculate and display the total and average of all expenses, or a message if none exist
  6. 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 "3" is selected:

  • If there are no expenses, print: No expenses to calculate.
  • If there are expenses, print the total and average in this format:
    Total: $X
    Average: $Y

Calculate the total by summing all :amount values. Calculate the average by dividing the total by the number of expenses.

For example, if the inputs are 3, then 5 (calculating when empty), the output should be:


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

--- 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, Coffee, 5.0, 1, Lunch, 15.0, 3, 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: Total: $20.0
Average: $10.0

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

Try it yourself

# Initialize the expenses array
expenses = []

# TODO: Write your code below
# Create a loop do that:
# - Displays the menu
# - Reads user input
# - Handles options 1, 2, 3, and 5
# 
# For option "1": prompt for name and amount, create hash, add to expenses
# For option "2": display all expenses or message if none
# For option "3": calculate and display total & average, or message if none
# For option "5": print "Goodbye!" and exit

All lessons in Fundamentals