出于某种原因,这个Ruby脚本无法正常工作

时间:2016-01-17 05:43:48

标签: ruby

我是ruby的新手,我正在尝试重新创建一个我用python制作的脚本,用红宝石来学习。到目前为止,我觉得这很简单,但程序根本不会运行。我收到此错误

  

“语法错误,意外的输入结束,期待keyword_end”

我不知道为什么,我用end

结束了我的循环

这是代码

#ruby version of work script

a = 0
b = 0
c = 0
i = " "
puts "Hello, please input the 3 character code."
i = gets.chomp
while i != "END"
    if i == "RA1"
        a += 1
    if i == "RS1"
        b += 1
    if i == "RF4"
        c += 1
    if i == "END"
        print "Complete"
    else
        puts "Please enter the 3 character code"
end

print "RA1: " + "#{a}" + "RS1: " + "#{b}" + "RF4: " + "#{c}"`

1 个答案:

答案 0 :(得分:3)

您的代码存在多个问题:

  • 您有语法错误。与python不同,在endif语句后,您需要else
  • 从您的代码中看起来您正在寻找if-elsif语句而不是多个if语句,因为else语句将是最后一个if。< / LI>
  • 您需要将i = gets.chomp放在while循环内,这样就不会进入无限循环。

尝试这样的事情:

#ruby version of work script

a = 0
b = 0
c = 0
i = " "
puts "Hello, please input the 3 character code."

while i != "END"
  i = gets.chomp
  if i == "RA1"
    a += 1
  elsif i == "RS1"
    b += 1
  elsif i == "RF4"
    c += 1
  elsif i == "END"
    print "Complete"
  else
    puts "Please enter the 3 character code"
  end
end

print "RA1: " + "#{a}" + "RS1: " + "#{b}" + "RF4: " + "#{c}"