Last active
July 30, 2018 18:40
-
-
Save Zorgatone/d764b0b5e4358ae1676caa2673e55bdf to your computer and use it in GitHub Desktop.
Codecademy - movies hash
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def get_title | |
print 'Enter movie title: ' | |
title = gets.chomp | |
if title.length < 1 | |
print 'Invalid title!' | |
return nil | |
else | |
return title.to_sym | |
end | |
end | |
def get_rating(title) | |
print "Enter rating for movie '#{title}': " | |
rating = gets.chomp | |
if rating.length > 1 | |
print 'Invalid rating' | |
return nil | |
end | |
rating = rating.to_i | |
if rating < 0 or rating > 4 | |
print 'Invalid rating' | |
return nil | |
else | |
return rating | |
end | |
end | |
movies = { | |
:Avatar => 4, | |
:'Lord of the Rings' => 3 | |
} | |
print 'Enter action: ' | |
choice = gets.chomp | |
case choice.downcase | |
when 'add' | |
title = get_title | |
if title.nil? | |
# Do nothing | |
elsif !movies[title].nil? | |
puts 'Entry already exists' | |
else | |
rating = get_rating title | |
unless rating.nil? | |
movies[title] = rating | |
puts "Added pair :#{title} => #{rating}" | |
end | |
end | |
when 'update' | |
title = get_title | |
if title.nil? | |
# Do nothing | |
elsif movies[title].nil? | |
puts "Entry doesn't esist" | |
else | |
rating = get_rating title | |
unless rating.nil? | |
movies[title] = rating | |
puts "Updated pair: :#{title} => #{rating}" | |
end | |
end | |
when 'display' | |
movies.each do |movie, rating| puts "#{movie}: #{rating}"; end | |
when 'delete' | |
title = get_title | |
if title.nil? | |
# Do nothing | |
elsif movies[title].nil? | |
puts "Entry doesn't esist" | |
else | |
movies.delete title | |
puts "Deleted movie '#{title}'" | |
end | |
else | |
puts 'Invalid command!' | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment