【问题标题】:For some reason, this Ruby script is not working出于某种原因,此 Ruby 脚本无法正常工作
【发布时间】:2016-04-22 11:45:45
【问题描述】:

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

“语法错误,意外的输入结束,期待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}"`

【问题讨论】:

标签: ruby


【解决方案1】:

您的代码存在多个问题:

  • 您有语法错误。与 python 不同,在每个 ifelse 语句之后都需要 end
  • 从您的代码看来,您正在寻找if-elsif 语句而不是多个if 语句,因为else 语句将是最后一个if
  • 您需要将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}"

【讨论】:

  • 谢谢,这非常有帮助。如何向 elsif 语句添加多个参数?就像在 python elif i in ("RA1", "RA2") 和 while 语句中一样,我可以在 ruby​​ 中输入 while i not in ("END", "end", "End") 吗?谢谢
  • 你可以做:["RA1", "RA2"].include?(i) 来测试类似i in ("RA1", "RA2") 的东西,对于not in 你可以做!["RA1", "RA2"].include?(i)
猜你喜欢
  • 1970-01-01
  • 2013-12-28
  • 1970-01-01
  • 1970-01-01
  • 2022-01-05
  • 2016-12-06
  • 2012-12-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多