Ruby帮助理解一些控制流并将多个条件放在一起

时间:2014-05-06 02:58:14

标签: ruby regex parameters conditional-statements control-flow

我创建了一个简单的“银行计划”作为练习,它似乎运作良好,直到我故意试图打破它看看会发生什么。我有一些代码用于确保正确输入引脚。

如果条目不包含数字,我想显示一条消息,并且我想弹出另一条消息,以确定它们输入的引脚是否是与其帐户关联的引脚。为此,我使用了一个除非/条件后跟一个if / else条件(代码的第一部分是方法中引用的一些正则表达式和存储它的哈希):

@accounts = {
    "bob" => { :pin => 1234, :balance => -100 },
    "mark" => { :pin => 2345, :balance => 1000000000 }
}

# Makes sure the user only types exactly 4 digits
def valid_pin_entry(pin)
    /^\d{4}$/ === pin
end
# Makes sure the user only types digits
def valid_number_entry(number)
    /^\d+$/ === number
end

def enter_pin_number(username)
    puts "Please type your pin number."
    response = gets.chomp 

    unless valid_pin_entry(response)
        puts "Your response must be 4 numbers in length.\n\n"
        enter_pin_number(username)
    else
        pin = response.to_i
        puts "Validating pin number..."
    end
    if validate_pin(@username, pin)
        puts "Your pin was successfully entered!\n\n"
    else
        puts "The pin number you entered was incorrect.\n\n"
        enter_pin_number(@username)
    end
end

似乎发生的情况是,如果输入的数字不正确,我会调用该方法重新开始。但它实际上并没有像我想象的那样开始。我正在寻找的回应是:

“您的回复必须是4个数字。”

“请输入你的密码。”

(这次正确输入。)

“验证密码......”

“您的图钉已成功输入!”

但我结束了这个:

Please type your pin number.
 a
Your response must be 4 numbers in length.

Please type your pin number.
 2345
Validating pin number...
Your pin was successfully entered!

The pin number you entered was incorrect.

Please type your pin number.
 2345
Validating pin number...
Your pin was successfully entered!

老实说,我很难理解为什么会发生这种情况,并且我认为这必须通过相同的方法来处理参数。我设法使用while来循环响应,但这并没有帮助我理解我的错误。我原来的程序显然很复杂,所以我把它发布在一个代码程序实验室中。

My bank_account.rb code

2 个答案:

答案 0 :(得分:1)

在下一行中,代码调用相同的函数(另一个函数调用)。

enter_pin_number(username)

该函数调用完成后,调用者恢复。要防止恢复,您需要明确return

unless valid_pin_entry(response)
    puts "Your response must be 4 numbers in length.\n\n"
    enter_pin_number(username)
    return # <------
else
    pin = response.to_i
    puts "Validating pin number..."
end

答案 1 :(得分:1)

当您决定对问题使用递归时,请确保在返回递归调用后不再执行任何代码。在函数式编程中,它被称为尾递归,可以优化为循环。

def enter_pin_number(username)
  puts "Please type your pin number."
  response = gets.chomp 

  unless valid_pin_entry(response)
    puts "Your response must be 4 numbers in length.\n\n"
    enter_pin_number(username)
  else
    pin = response.to_i
    puts "Validating pin number..."

    if validate_pin(@username, pin)
      puts "Your pin was successfully entered!\n\n"
    else
      puts "The pin number you entered was incorrect.\n\n"
      enter_pin_number(@username)
    end
  end
end