Add Book
Part of the Logic & Flow section of Coddy's Ruby journey — lesson 29 of 56.
Add the 1. Add Book option to the menu loop. When the user picks it, prompt for the book's title, author, and genre, then push a new hash into the library array.
Every book starts unread (read: false).
Challenge
EasyExtend the menu loop. When the choice is "1":
printthe promptTitle:and read the titleprintAuthor:and read the authorprintGenre:and read the genre- Push a hash
{ title:, author:, genre:, read: false }intolibrary - Print
Book added!
Keep the 5. Exit behavior from the previous lesson (prints Goodbye! and breaks).
For inputs 1, The Hobbit, Tolkien, Fantasy, then 5, the output ends with:
Choose an option: Title: Author: Genre: Book added!
--- Library Manager ---
...
Choose an option: Goodbye!Cheat sheet
Adding a book to an array using a hash with push:
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!"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
end
# TODO: handle choice == "1", prompt for title/author/genre,
# push a hash into library, print "Book added!"
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