我做到了这一点,但不知道在哪里添加.to_i和.to_sym方法,因为我假设我把它们放在错误的地方。有人可以帮我吗?当我测试代码时,它说“未定义的方法`to_sym ='代表nil:NilClass”
movies = {
spiderman: 3,
superman: 4,
batman: 5
}
puts "what movie do you like?"
choice = gets.chomp
case choice
when 'add'
puts "What movie do you want to add?"
title.to_sym = gets.chomp
puts "what is the rating of that movie?"
rating.to_i = gets.chomp
movies[title]=rating
puts "Added!"
when 'update'
puts "What movie would you like to update?"
title = gets.chomp
puts "Updated!"
when 'display'
movies.each do |movies, ratings|
puts "#{movies}: #{ratings}"
end
puts "Movies!"
when 'delete'
puts "What movie would you like to delete from the list?"
title = gets.chomp
puts "Deleted!"
else
puts "Error!"
end
答案 0 :(得分:1)
除了[]=
之外,没有形式foo=
或to_sym=
的方法,就像你的代码中的普通Ruby一样。如果要将用户输入作为符号,可以执行以下操作:
title = gets.chomp.to_sym
如果你想得到一个整数,你可以这样做:
rating = gets.to_i
我不知道为什么在后一种情况下你有chomp
。