关于代码十年的Ruby问题



codecademy上一直出现错误信息,我不明白为什么,欢迎任何帮助!

下面是我的代码:
  movies={ 
        Lala:3, 
        VV:4 
    } 
    puts "What to do?" 
    choice=gets.chomp
    case choice 
    when "add" 
      puts "What movie you wanna add?" 
      title=gets.chomp 
      if movies[title.to_sym].nil? 
        puts "What rating for the movie?" 
        rating=gets.chomp 
        movies[title.to_sym]=rating.to_i 
        puts "Movie and rating added!" 
      else 
        puts "movie already in list..." 
      end
    when "update" 
      puts "what movie to update?" 
      title=gets.chomp 
      if movies[title.to_sym].nil? 
        puts "Error movie not in list" 
      else 
        puts "New rating?" 
        rating=gets.chomp 
        movies[title.to_sym]=rating.to_i 
        puts "Rating updated" 
      end 
    when "display" 
      movies.each do |movies,rating| 
        puts "#{movies}: #{rating}" 
      end 
    when "delete" 
      puts "Movie to delete?" 
      title = gets.chomp
        if movies[title.to_sym].nil?
            puts "Movie not found"
        else
            movies.delete(title.to_sym)
            puts "Movie deleted"
    end

这是错误信息:

(ruby): syntax error, unexpected tIDENTIFIER, expecting $end
...     Lala:3,      VV:4  }  puts "What to do?"  choice=gets.c...
... 

帮助!拜托!谢谢! !

您需要在代码中再添加一个end

movies={ 
    Lala:3, 
    VV:4 
} 
puts "What to do?" 
choice=gets.chomp
case choice 
when "add" 
  puts "What movie you wanna add?" 
  title=gets.chomp 
  if movies[title.to_sym].nil? 
    puts "What rating for the movie?" 
    rating=gets.chomp 
    movies[title.to_sym]=rating.to_i 
    puts "Movie and rating added!" 
  else 
    puts "movie already in list..." 
  end
when "update" 
  puts "what movie to update?" 
  title=gets.chomp 
  if movies[title.to_sym].nil? 
    puts "Error movie not in list" 
  else 
    puts "New rating?" 
    rating=gets.chomp 
    movies[title.to_sym]=rating.to_i 
    puts "Rating updated" 
  end 
when "display" 
  movies.each do |movies,rating| 
    puts "#{movies}: #{rating}" 
  end 
when "delete" 
  puts "Movie to delete?" 
  title = gets.chomp
    if movies[title.to_sym].nil?
        puts "Movie not found"
    else
        movies.delete(title.to_sym)
        puts "Movie deleted"
end
<=# Need an extra `end` here.

您没有关闭case语句。

您在这里得到了许多错误的建议,因为显然有些人不熟悉Ruby 1.9风格的散列声明。在Ruby 1.9或更高版本中,此代码中没有语法错误。如果你使用的是过时的Ruby 1.8.7,你会得到错误。

缺少一个end语句,您似乎因为不规则缩进而错过了它:

when "delete" 
  puts "Movie to delete?" 
  title = gets.chomp
    if movies[title.to_sym].nil?
        puts "Movie not found"
    else
        movies.delete(title.to_sym)
        puts "Movie deleted"
    end # Omitted in original
 end

不清楚为什么if得到了额外的缩进,但它显然缺少了自己的end

除此之外,我已经用Ruby 1.9测试了你的代码,这是一个严重过时的Ruby版本,它可以工作。最近的版本也没有问题,比如最新的2.3.1。

解决这个问题的方法是使用一个不太旧的Ruby版本。Ruby 1.8.7一直维持到2013年,但现在它已经死了。甚至Ruby 1.9也不再支持许多gem和应用程序了。

如果可能的话,获取当前版本的Ruby并尝试您的代码。应该可以。

注意,这里的一个问题是不规则缩进,这使得发现语法错误异常困难。

最新更新