Menu
Coddy logo textTech

Project Overview

Part of the Logic & Flow section of Coddy's Ruby journey — lesson 28 of 56.

You're going to build a small library manager: a menu-driven program that keeps track of books and lets the user add, search, filter, and mark them as read.

Each book is a hash with these keys:

{
  title:  "The Great Gatsby",
  author: "F. Scott Fitzgerald",
  genre:  "Fiction",
  read:   false
}

You'll keep all of them in an array called library and drive the whole thing from a loop do that prints a menu and reads a choice. Each lesson adds one option to the menu:

  • 1. Add a book
  • 2. Search by title
  • 3. Filter by genre
  • 4. Mark a book as read
  • 5. Exit

This first lesson sets up the empty library, the menu loop, and the exit option. The other options will start as empty branches you fill in later.

challenge icon

Challenge

Beginner

Initialize an empty library array, then start a loop do that:

  1. Prints the menu (exact format below)
  2. Reads the user's choice with gets.chomp
  3. If choice is "5", prints Goodbye! and breaks out of the loop

The menu must look exactly like this:

--- Library Manager ---
1. Add Book
2. Search By Title
3. Filter By Genre
4. Mark As Read
5. Exit
Choose an option: 

Use print for the Choose an option: prompt so the cursor stays on the same line.

For input 5, the output is:

--- Library Manager ---
1. Add Book
2. Search By Title
3. Filter By Genre
4. Mark As Read
5. Exit
Choose an option: Goodbye!

Cheat sheet

Each book is a hash stored in a library array:

library = []

book = {
  title:  "The Great Gatsby",
  author: "F. Scott Fitzgerald",
  genre:  "Fiction",
  read:   false
}

Use loop do with break to build a menu-driven program. Use print (not puts) to keep the cursor on the same line as the prompt:

loop do
  puts "--- Library Manager ---"
  puts "1. Add Book"
  puts "5. Exit"
  print "Choose an option: "
  choice = gets.chomp

  if choice == "5"
    puts "Goodbye!"
    break
  end
end

Try it yourself

# TODO: initialize an empty library array

# TODO: loop do, print menu, read choice, exit on "5"
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow