Ruby语法错误,意外的$ end

时间:2015-07-21 13:25:12

标签: ruby if-statement

从昨天开始,我一直在用CodeCademy和一些Ruby玩游戏,我感觉好像我正在抓住它,但是有一些问题变得明显了。

这段代码有什么问题?我一直收到错误:

  

(ruby):15:语法错误,意外$ end,期待keyword_end

print "What grade did you get on your final?"
grade = gets.chomp
if grade > 1
    puts "You're just making that up! Really?"
answer = gets.chomp
yes = true
no = false

if answer == true
    print "Oh, that's awesome!"
if answer == false
    print "Dang, I thought you were serious."
else
    print "What? I don't understand."
end

3 个答案:

答案 0 :(得分:1)

通过适当的缩进变得清晰

print "What grade did you get on your final?"
grade = gets.chomp
if grade > 1
  puts "You're just making that up! Really?"
  answer = gets.chomp
  yes = true
  no = false

  if answer == true
    print "Oh, that's awesome!"
    if answer == false
      print "Dang, I thought you were serious."
    else
      print "What? I don't understand."
    end

Ruby中的每个if都需要相应的end。您有三个if个,只有一个end。因此,只有最后一个if answer == false具有匹配的end,您还需要另外两个。{/ p>

答案 1 :(得分:0)

您有两个if语句没有相应的end

if grade > 1
  puts "You're just making that up! Really?"
end

if answer == true
  print "Oh, that's awesome!"
end

在不相关的说明中,我认为您需要puts而不是print

此外,当你有一个布尔值时,你不需要做

if my_boolean == true
  # do something
end

这与做

完全相同
if my_boolean
  # do something
end

最后,布尔值只有两个可能的值,truefalse。您拥有的最后一个else声明没有意义,因为它会在answer == true时被激活,而您已经拥有该声明。

答案 2 :(得分:0)

您需要结束每个if。 你可以这样做:

puts "What grade did you get on your final?"
grade = gets.chomp

if grade > 1
  puts "You're just making that up! Really?"
end

answer = gets.chomp

if answer == "yes"
  print "Oh, that's awesome!"
elsif answer == "no"
  print "Dang, I thought you were serious."
else
  print "What? I don't understand."
end

或者可以是这样的,您不需要使用end

puts "What grade did you get on your final?"
grade = gets.chomp

# HERE
puts "You're just making that up! Really?" if grade > 1

answer = gets.chomp

if answer == "yes"
  print "Oh, that's awesome!"
elsif answer == "no"
  print "Dang, I thought you were serious."
else
  print "What? I don't understand."
end