Menu
Coddy logo textTech

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 icon

Challenge

Easy

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

  1. print the prompt Title: and read the title
  2. print Author: and read the author
  3. print Genre: and read the genre
  4. Push a hash { title:, author:, genre:, read: false } into library
  5. 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
quiz iconTest yourself

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

All lessons in Logic & Flow