gpt4 book ai didi

ruby - 理解 Ruby - 未定义的局部变量

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

我一直在研究 Ruby,并遇到过这种奇怪的行为。谁能告诉我为什么会这样?

如果我运行:

def my_fn
if false then
a = {:a=>10, :b=>20}
end
puts a.class
a || {}
end

并打印代码编译成功的结果并返回 {}。但是如果我将代码更改为:

def my_fn
puts a.class
a || {}
end

它不返回 {} 但抛出错误。 “‘my_fn’:main:Object (NameError) 的未定义局部变量或方法‘a’”

a 不应该只是 nil 而不会导致错误吗?

最佳答案

这是因为 - The local variable is created when the parser encounters the assignment, not when the assignment occurs .

在第一个代码解析器中看到 a = {:a=>10, :b=>20} 行,所以创建了一个变量,但没有赋值发生。因此 anilAs per the all known facts 一个|| {} 返回 {}

在第二个代码中,解析器没有看到 a 发生任何赋值,所以 a 没有被创建为局部变量,您也没有创建名为一个。因此,当您尝试使用 a 时,得到了您报告的有效错误,即未定义的局部变量或方法“a”

关于ruby - 理解 Ruby - 未定义的局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21704302/

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