Menu
Coddy logo textTech

Search By Title

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

Add the 2. Search By Title option. The user types a search term, and the program prints every book whose title contains that term, case-insensitive.

This is where select from the previous chapter pays off, one block, no manual loop:

matches = library.select do |book|
  book[:title].downcase.include?(query.downcase)
end
challenge icon

Challenge

Easy

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

  1. print the prompt Search title: and read the query
  2. Use select to find books whose title (case-insensitive) includes the query
  3. If there are no matches, print No matches.
  4. Otherwise print one line per match in this format: <title> by <author>

Keep the 1 (Add Book) and 5 (Exit) behaviors from the previous lessons.

For inputs 1, The Hobbit, Tolkien, Fantasy, 2, hobbit, then 5, the matching block of output looks like:

Choose an option: Search title: The Hobbit by Tolkien

Cheat sheet

Use select with downcase.include? for case-insensitive title search:

matches = library.select do |book|
  book[:title].downcase.include?(query.downcase)
end

Print results or a fallback message:

if matches.empty?
  puts "No matches."
else
  matches.each { |book| puts "#{book[:title]} by #{book[:author]}" }
end

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!"
  end
  # TODO: handle choice == "2", prompt for query, select matching books,
  # print "No matches." or one line per match: "<title> by <author>"
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