A Night At The Movies -- Looping Back


#1

My code ended up passing and looking similar to the original entry (with a few minor adjustments) for this exercise, but I am now wanting to add a loop to the functionality such that when a task is completed (add, update, display, delete) the program will ask the user if they would like to complete another action. I'm sufficiently new enough at programming that I'm not sure where to start.

Here is my code:

movies = { Hackers: 4,
The_Shawshank_Redemption: 4,
Lucky_Number_Slevin: 4
}

puts "What would you like to do?"
puts "--Add:"
puts "--Update:"
puts "--Display:"
puts "--Delete:"
puts "--Exit:"
choice = gets.chomp.downcase
case choice

when "add" then print "Please provide the name of the movie: "
title = String(gets.chomp)
if movies[title.to_sym].nil?
print "Please provide a rating for #{title}: "
rating = Integer(gets.chomp)
movies[title.to_sym] = rating.to_i
puts "Added!"

else
    puts "That movie is already in the database!"
end

when "update" then print "Type the name of the movie you wish to update: "
title = String(gets.chomp)
if movies[title.capitalize.to_sym].nil?
puts "That movie is not yet in the database!"

else
    print "Please provide a rating for #{title}: "
    rating = Integer(gets.chomp.capitalize)
    movies[title.to_sym.capitalize] = rating.to_i
    puts "Updated!"
end

when "display" then
movies.each do |name, rating|
name = name.to_s.split("_").collect(&:capitalize).join(" ")
puts "#{name}: #{rating}"
end

when "delete" then
print "Type the name of the movie you wish to delete: "
title = String(gets.chomp)
if movies[title.capitalize.to_sym].nil?
puts "That movie is not in the database and therefore cannot be deleted."

else 
    movies.delete(title)
end

when "exit" then
puts "Goodbye."

else
puts "That was not a valid entry."

end


#2

@arjofocolovi Care to share your expertise with this next little puzzle?


#3

You first need to decide where to place your loop. What part of your code do you need to be repeated?


#4

Sorry for the delay! Holidays over here in the States.

I want to repeat the following section.

puts "What would you like to do?"
puts "--Add:"
puts "--Update:"
puts "--Display:"
puts "--Delete:"
puts "--Exit:"
choice = gets.chomp.downcase
case choice

I want it to loop back to the original options until the user selects 'Exit' at which time the program will simply say 'goodbye'.

I know that an N.times method call wouldn't be ideal since that's for a set number of loops. Would I use another When / Case loop?


#5

Hm, you would also need the execution of the commands inside your loop, because you want to be able, for example, to display, then update, then display, etc...

Now, as you said, you can't use a loop based on a defined number. Instead, a solution could be to end your loop when the user enters the 'exit' command. Which means that your condition will need to check for the value of the command entered ^^.