Menu
Coddy logo textTech

Filter By Genre

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

Add the 3. Filter By Genre option. The user types a genre and the program lists every book in that exact genre, case-sensitive match this time.

You'll also report a count, using count from the previous chapter.

challenge icon

Challenge

Easy

Extend the menu loop. When the choice is "3":

  1. print the prompt Genre: and read it
  2. select books whose :genre equals the input exactly
  3. Print one line per match: <title> by <author>
  4. After the list, print Total: <n> where n is the count of matches (use count or matches.length)

Keep all earlier branches intact.

For inputs adding two Fantasy books and one Sci-Fi book, then filtering by Fantasy and exiting, the filter block should print both fantasy books and Total: 2.

Cheat sheet

Filter records by exact field match and count results:

print "Genre: "
genre = gets.chomp

matches = books.select { |b| b[:genre] == genre }

matches.each { |b| puts "#{b[:title]} by #{b[:author]}" }
puts "Total: #{matches.length}"

Try it yourself

library = []

loop do
  puts "--- Library Manager ---"
  puts "1. Add Book"
  puts "2. Search By Title"
  puts "3. Filter By Genre"
  puts "4. Mark As Read"
  puts "5. Exit"
  print "Choose an option: "
  choice = gets.chomp
  if choice == "5"
    puts "Goodbye!"
    break
  elsif choice == "1"
    print "Title: "
    title = gets.chomp
    print "Author: "
    author = gets.chomp
    print "Genre: "
    genre = gets.chomp
    library.push({ title: title, author: author, genre: genre, read: false })
    puts "Book added!"
  elsif choice == "2"
    print "Search title: "
    query = gets.chomp
    matches = library.select { |b| b[:title].downcase.include?(query.downcase) }
    if matches.empty?
      puts "No matches."
    else
      matches.each { |b| puts "#{b[:title]} by #{b[:author]}" }
    end
  end
  # TODO: handle choice == "3", prompt for genre,
  # select matching books, print each, then "Total: <n>"
end
quiz iconTest yourself

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

All lessons in Logic & Flow