刚开始学习Ruby;为什么我的代码在Codeacademy环境中可以正常工作,而在Mac Terminal中却不行?

8fsztsew  于 2023-04-05  发布在  Ruby
关注(0)|答案(1)|浏览(170)

完成了一个关于Hash & Symbols的迷你项目,想看看它在终端中是如何运行的。
它在Codeacademy中执行得很好,但在终端中它打印出错误的响应,似乎是因为它没有正确引用哈希数组。
尽管我给予终端的输入不存在于哈希数组中,它还是打印出“It's already on the list!”
是codeacademy教得不对,还是我的代码有一些特定于终端的问题?

movies = {
  Hackers: 8.0,
  Gladiator: 9.0,
}

puts "Would you like to add, update, display, or delete movies?"
choice = gets.chomp

case choice
when "add"
  puts "What's the movie called?"
  title = gets.chomp.to_sym
  puts "What would you rate it out of 10?"
  rating = gets.chomp.to_i
    if movies[title.to_sym] = nil
    movies[title.to_sym] = rating.to_i
    puts "The movie has been added!"
    else puts "It's already on the list!"
    end
du7egjpx

du7egjpx1#

=是赋值运算符,而==是比较运算符。=运算符用于将值赋值给变量,而==运算符用于比较两个变量或常量。了解两者的区别很重要,Code Academy环境可能会解决这个问题。Ruby也有一个===运算符。

movies = {
  Hackers: 8.0,
  Gladiator: 9.0,
}

puts "Would you like to add, update, display, or delete movies?"
choice = gets.chomp

case choice
when "add"
  puts "What's the movie called?"
  title = gets.chomp.to_sym
  puts "What would you rate it out of 10?"
  rating = gets.chomp.to_i
    if movies[title.to_sym] == nil
      movies[title.to_sym] = rating.to_i
      puts "The movie has been added!"
    else 
      puts "It's already on the list!"
    end

相关问题