2014-02-19 68 views
-1

我已經做到了這一步,但不知道在哪裏添加.to_i和.to_sym方法,因爲我假設我把它們放在錯誤的地方。有人可以幫我嗎?當我從測試的代碼它說:「未定義的方法`to_sym =」的零:NilClass」將字符串轉換爲Ruby中的符號和整數

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 

回答

1

此外[]=,沒有形式foo=,或to_sym=,在你的代碼的方法,在平原紅寶石。如果你想獲得用戶輸入的符號,你可以這樣做:

title = gets.chomp.to_sym 

如果你想獲得一個整數,你可以這樣做:

rating = gets.to_i 

我不知道爲什麼你有在後一種情況下爲chomp

+0

好的。這工作。我現在明白了。我習慣於在獲取結束時添加chomp。不過謝謝 – user3324987