Extracurricular Activities


#1

movies = {
Memento: 3,
Primer: 4,
Ishtar: 1
}

puts "What would you like to do?"
puts "-- Type 'add' to add a movie."
puts "-- Type 'update' to update a movie."
puts "-- Type 'display' to display all movies."
puts "-- Type 'delete' to delete a movie."

choice = gets.chomp.downcase
case choice
when 'add'
puts "What movie do you want to add?"
title = gets.chomp
if movies[title.to_sym].nil?
puts "What's the rating? (Type a number 0 to 4.)"
rating = gets.chomp
movies[title.to_sym] = rating.to_i
puts "#{title} has been added with a rating of #{rating}."
else
puts "That movie already exists! Its rating is #{movies[title.to_sym]}."
end
when 'update'
puts "What movie do you want to update?"
title = gets.chomp
if movies[title.to_sym].nil?
puts "Movie not found!"
else
puts "What's the new rating? (Type a number 0 to 4.)"
rating = gets.chomp
movies[title.to_sym] = rating.to_i
puts "#{title} has been updated with new rating of #{rating}."
end
when 'display'
movies.each do |movie, rating|
puts "#{movie}: #{rating}"
end
when 'delete'
puts "What movie do you want to delete?"
title = gets.chomp
if movies[title.to_sym].nil?
puts "Movie not found!"
else
movies.delete(title.to_sym)
puts "#{title} has been removed."
end
else
puts "Sorry, I didn't understand you."
end

I'm trying a few extracurricular activities. The code works, but I'm just exploring some things.

  1. Memento is already in the movie hash. If I add memento, the program accepts it as a new entry. How could I get it to recognize this is the same entry as what is in there?

  2. When assigning a rating to the movies it asks for a rating of 0-4 if I enter 10 it will take the entry. How could I have it recognize that 10 is not a correct answer and prompt for another entry?

  3. Broad question. For everything, really, if I don't enter an acceptable answer it will respond but the program ends. How could I get the program to keep asking until it receives an acceptable answer? I know this involves a loop, but I just seem to create an infinite loop so I need some help.


#2

I'll just give you hints for now :

  1. Just downcase or upcase when you make your comparisons.

  2. Use the to_i method (conversion to integers) so that you can make your comparisons on numbers instead of characters.

  3. You want an infinite loop essentially, what you need is just a condition to break out of it. this condition will be based on the value of the variable getting the input.