gpt4 book ai didi

ruby - 递归和 Kernel#rand (Ruby) 的奇怪行为

转载 作者:数据小太阳 更新时间:2023-10-29 09:03:27 25 4
gpt4 key购买 nike

我在 Ruby 中有一个这样的方法:

def guess
random_guess = rand(4)
if random_guess == 0
guess
end

puts random_guess
end
guess

正如你所看到的,它的目的是生成一个介于 0 和 4 之间的随机数,然后如果该数字为 0,则重复出现。这个想法是为了防止该方法打印出 0。但是,它似乎并不是出于某种奇怪的原因这样做。例如,这是 IRB 中的一个示例,当 random_guess 获得 0 的值时:

2.2.0 :001 > def guess
2.2.0 :002?> random_guess = rand(4)
2.2.0 :003?> if random_guess == 0
2.2.0 :004?> guess
2.2.0 :005?> end
2.2.0 :006?>
2.2.0 :007 > puts random_guess
2.2.0 :008?> end
=> :guess
2.2.0 :009 > guess
2
0
0
0
0
=> nil
2.2.0 :010 >

当它没有得到 0 值时,程序正常运行并简单地打印出该范围内的任何其他随机数:

2.2.0 :010 > guess
1
=> nil
2.2.0 :011 >

我想知道的是为什么程序在 random_guess 为 0 时发生的递归行为如此奇怪。看起来它是重复出现的,但它似乎并没有在正确的地方停止条件,即当 random_guess 不为 0 时。为什么会这样?

最佳答案

random_guess0 时,guess 递归调用自身,这是正常工作的。您看到的输出是因为 puts random_guess 在递归之后 执行。所以当你看到输出时,例如:

3
0
  1. guess 是这样调用的:random_guess 得到 0,所以调用 guess
  2. inner guess 中,random_guess 得到 3,将当前 random_guess,即 3。退出内部 猜测
  3. random_guess的值放入outter guess,即0,然后退出。

关于ruby - 递归和 Kernel#rand (Ruby) 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29691076/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com