dimanche 29 avril 2018

How do I return an error message when the user inputs the wrong info? in Ruby

I'm very much a beginner, learning Ruby, and I'm stuck on how to insert an error message in the loop below when the user inputs the wrong info.

So far, the method works by displaying a numbered list and asking the user to input either a number or name from the list. The block loops until the user enters "exit," after which the program ends. I want to add a line or two that puts an error message like, "Sorry, I don't seem to understand your request" if the user inputs something that is not on the list (name/number) and is not the word "exit."

It seems like it should be simple to add in an error message, but I can't seem to figure it out. Any advice?

My current code below! Thanks in advance!

def start
  display_books
  input = nil
  while input != "exit"
    puts ""
    puts "What book would you more information on, by name or number?"
    puts ""
    puts "Enter list to see the books again."
    puts "Enter exit to end the program."
    puts ""
    input = gets.strip
    if input == "list"
      display_books
    elsif input.to_i == 0
      if book = Book.find_by_name(input)
        book_info(book)
      end
    elsif input.to_i > 0
      if book = Book.find(input.to_i)
        book_info(book)
      end
    end
  end
  puts "Goodbye!!!"
end

Aucun commentaire:

Enregistrer un commentaire