以下是Codecademy提供的代码:
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
在代码的显示分支中,为什么codecademy使用|movie, rating| and "#{movie}: #{rating}"
?没有为电影定义变量。
因为电影变量不应该是|title, rating| and "#{title}: #{rating}"
?
答案 0 :(得分:1)
movies = {
Memento: 3,
Primer: 4,
Ishtar: 1
}
movies.each do |movie, rating|
puts "#{movie}: #{rating}"
end
您可以将|movie, rating|
视为他们创建的全新变量,以使用each
循环。
基本上,each
循环遍历movies
哈希。在movies
哈希中,我们有电影标题及其相对评级。所以当他们迭代那个哈希时,他们基本上会在那里拿起每个细节并使用变量movie, rating
,即:
# 1st iteration
movie = Memento
rating = 3
# 2nd iteration
movie = Primer
rating = 4
# 3rd iteration
movie = Ishtar
rating = 1
您可以将这些变量命名为您想要的任何名称,但最好让您的代码易于阅读,因此他们为每个电影标题使用movie
,并为每个电影标题使用rating
相对评级