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)
endChallenge
EasyExtend the menu loop. When the choice is "2":
printthe promptSearch title:and read the query- Use
selectto find books whose title (case-insensitive) includes the query - If there are no matches, print
No matches. - 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 TolkienCheat sheet
Use select with downcase.include? for case-insensitive title search:
matches = library.select do |book|
book[:title].downcase.include?(query.downcase)
endPrint results or a fallback message:
if matches.empty?
puts "No matches."
else
matches.each { |book| puts "#{book[:title]} by #{book[:author]}" }
endTry 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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String Methods OverviewString InterpolationIterating Over StringsSplit and JoinRecap - String Weaver4Blocks, Procs & Lambdas
What is a Block?do..end vs BracesThe yield KeywordBlock ParametersProcs and LambdasRecap - Custom Iterator7Hashes Part 2
Hash.new with DefaultsIterating HashesNested HashesMerging and TransformingRecap - Frequency Counter10Project - Student Records
Project OverviewAdd Student5Enumerable Powerhouse
Select and RejectChaining MapReduce / Injectcount, all?, any?, none?group_by and partitionsort_by, min_by, max_byRecap - Data Pipeline8Advanced Decision Making
Case with Classes & RegexMulti-value whenTernary OperatorInline if / unlessRecap - Grade Classifier