Ruby While循环不能正常工作

时间:2015-12-06 19:56:44

标签: ruby if-statement while-loop user-input

我一直在尝试在ruby中创建一个响应用户输入的while循环。 应该发生的是当用户正确输入单词“Omega”时它结束循环并显示一条消息,如果输入单词“hint”,则显示一条消息并且循环重复,其他任何内容都将具有“再试一次“显示的消息。发生的事情是,无论输入什么,循环只询问原始问题。

任何人都可以找到我的代码有什么问题,谢谢

@GateOneLocked = true
GateOnePassword = String.new('Omega')
GateOneHint= String.new('hint')
#Omega is supposed to be the correct password
while (@GateOneLocked == true) do
puts 'What is the password?'
passwordEntered = gets.to_s
    if (@passwordEntered == @GateOnePassword)
        @GateOneLocked == false
    else if (@passwordEntered != @GateOneHint)
    puts "This is a hint: the password is 'Omega'"
    puts " "
    puts " "
    else
        puts "wrong password, try again"
        puts " "
        puts " "
    end
    end
end
puts 'You entered the correct password!'

2 个答案:

答案 0 :(得分:1)

@GateOneLocked == false应为@GateOneLocked = false

附加说明:

    ruby变量名中的
  • 遵循与C#/ Java不同的约定,而不是 GateOneLocked开发人员写gate_one_locked

  • 无需撰写String.newvariable = "your_string"已足够(GateOnePassword = 'Omega'

  • while(@GateOneLocked)已足够 - 无需检查是== true

答案 1 :(得分:0)

我对你的代码做了几处修复。我将else if更改为elsif并将@添加到缺少它的变量引用中,以便您的代码保持一致。 (除非你在课堂上使用这段代码,否则我实际上会抛弃它们。)我改变了你的@GateOneLocked == false以使用赋值运算符而不是比较运营商。最重要的是,也许,我添加了一个chomp调用,它将从用户的输入中删除\n(新行字符)。另外,我将elsif中的比较更改为==,以便您的用户可以请求提示,这是我认为您的意图。

@GateOneLocked = true
@GateOnePassword = String.new('Omega')
@GateOneHint= String.new('hint')
#Omega is supposed to be the correct password
while (@GateOneLocked == true) do
    puts 'What is the password?'
    @passwordEntered = gets.chomp.to_s
    if (@passwordEntered == @GateOnePassword)
        puts "abc"
        @GateOneLocked = false
    elsif (@passwordEntered == @GateOneHint)
        puts "This is a hint: the password is 'Omega'"
        puts " "
        puts " "
    else
        puts "wrong password, try again"
        puts " "
        puts " "
    end
end
puts 'You entered the correct password!'