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
EasyExtend the menu loop. When the choice is "3":
printthe promptGenre:and read itselectbooks whose:genreequals the input exactly- Print one line per match:
<title> by <author> - After the list, print
Total: <n>wherenis the count of matches (usecountormatches.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
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