我正在尝试为学校写一个Twenty-Questions应用程序,而且我已经达到了减速带。
在第26行,我收到错误:20q2.rb:26: warning: string literal in condition
。
此外,我有一个评分系统告诉用户他们的最终得分是什么,并且在每个问题之后打印得分时应该在测验结束时显示。
代码工作正常,所以如果有人可以帮助我解决这两个问题,那将是很好的。
以下是代码:
#list quesions in an array
QANDA = [["Is the sky blue?", "y"],["Is it dark at night?", "y"],
["Is this a yes or no question?", "y"],
["Is this a short answer question", "n"],
["Is this program written in rails?", "n"],["Is this program written in ruby?", "y"]]
#create a variable for the scoring system
num = 0
#create a loop to ask questions automatically
QANDA.each do |options|
puts options[0]
#ask for user input
puts "enter y or n"
ans = gets.chomp
ansdown = ans.downcase
#compair user input with correct answer
if ansdown == options[1]
#add number to score and give praise
num = num + 1
puts "correct"
#give shame
elsif ansdown == "n"
puts "incorrect"
#reprint question if responce is invalid
end
if ansdown != "y" && "n" && "Y" && "N"
puts "invaild input, please try again. Enter y/n only."
redo
end
#convert num to a string
score = num.to_s
#print score
puts "you got " + score + " of 6 questions right."
#shame the foolish
if num <= 3
puts "you did a pretty bad job"
#praise the wise
elsif num > 4
puts "great job!"
elsif num == 4
puts "not to bad"
end
end
答案 0 :(得分:1)
if ansdown != "y" && "n" && "Y" && "N"
除了第一个条件之外,这条线对我没有意义。你需要根据你想要的东西来解决这个问题。这是“字符串文字”警告。
这只是一个警告,在Ruby中字符串被认为是真的,但我猜这不是你想要的。
我建议
unless ["y","n"].include? ansdown
你需要小写,但你已经在做了。
关于第二个问题,请改进你的缩进。我希望你的得分代码太深了。它应该在each
块之外
答案 1 :(得分:1)
以下情况有误:
if ansdown != "y" && "n" && "Y" && "N"
因为它将被解释如下:
if (ansdown != "y") && ("n") && ("Y") && ("N")
您可能想要做的是:
if ansdown != "y" && ansdown != "n" && ansdown != "Y" && ansdown != "N"
或简而言之,你可以这样做:
if !["y", "Y","n","N"].include?(ansdown)
如果您使用的是ActiveSupport,也可以使用exclude?
(纯Ruby中不可能):
if ["y", "Y","n","N"].exclude?(ansdown)