gpt4 book ai didi

ruby 错误 : Not Finding Variable Defined in Loop

转载 作者:行者123 更新时间:2023-12-04 10:54:14 25 4
gpt4 key购买 nike

我在 Ruby 中有代码,它在循环中定义了一个变量。

print("What difficulty do you want on a scale of 1-5?\n")
loop do
difficulty = gets.to_i
break if difficulty == 1 or difficulty == 2 or difficulty == 3 or difficulty == 4 or difficulty == 5
end
range = 10 if difficulty == 1
range = 100 if difficulty == 2
range = 500 if difficulty == 3
range = 1000 if difficulty == 4
range = 5000 if difficulty == 5

我收到一个错误,指出变量难度未定义。我认为这是循环中的一个问题。我不知道如何将它实现为另一种形式来达到同样的目的。有没有办法让变量成为全局变量?我试过寻找其他方法来制作另一种格式,但没有任何帮助。

最佳答案

您可以在循环之外定义它,否则它会受到范围限制。

尝试:

difficulty_range = {
1 => 10,
2 => 100,
3 => 500,
4 => 1000,
5 => 5000
}

difficulty = nil

loop do
print("What difficulty do you want on a scale of 1-5?\n")
difficulty = gets.to_i
break if (1..5).include?(difficulty)
end

p difficulty_range[difficulty]

关于 ruby 错误 : Not Finding Variable Defined in Loop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59308287/

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