英文:
Just started learning Ruby; Why does my code work properly in the Codeacademy environment but not in the Mac Terminal?
问题
完成了一个关于散列和符号的小项目,想看看它在终端中的运行情况。
它在Codeacademy中执行得很完美,但在终端中却打印出了错误的响应,似乎是因为它没有正确引用散列数组。
尽管我在终端中提供的输入在散列数组中不存在,它却打印出"它已经在列表中!"。
是Codeacademy在教我错误的方法,还是我的代码中存在一些终端特定的问题?
英文:
Completed a mini project on Hashes & Symbols, and wanted to see how it ran in the terminal.
It executes perfectly in Codeacademy, but in the terminal it's printing out the wrong responses, seemingly because it's not correctly referencing the hash array.
Despite the input I give the terminal not existing in the hash array, it prints "It's already on the list!"
Is codeacademy teaching me incorrectly, or is there some terminal-specific issue with my code?
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
答案1
得分: 1
= 是一个赋值运算符,== 是一个比较运算符。= 运算符用于将值赋给一个变量,而 == 运算符用于比较两个变量或常量。了解这个区别非常重要,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
英文:
= is a assignment operator and == is a comparison operator. = operator is used to assign value to a variable and == operator is used to compare two variable or constants. It is important to know the difference, the Code Academy environment is maybe accounting for the issue. Ruby also has a ===
operator.
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论