为什么ruby即使从不执行变量赋值代码也要定义变量?

编程入门 行业动态 更新时间:2024-10-28 13:19:54
本文介绍了为什么ruby即使从不执行变量赋值代码也要定义变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

给定以下代码:

a = true # let's assign `a` a value

# and let's test if calling `b`, an unassigned variable, throws an error
begin
  puts "The value of b is: #{b.inspect}"
rescue NameError => e
  puts "Caught an error: #{e}"
end

a || b = true # the assignment should never be executed because `a` is `true`

puts "The value of b is: #{b.inspect}" # will calling `b` still raise an error?

我们得到以下结果:

Caught an error: undefined local variable or method `b' for main:Object
The value of b is: nil

即使我们期望第二次调用 b 会引发错误,但我们看到 b 现在实际上是 nil.

Even though we expected calling b to raise an error the second time, we see that b is now, in fact, nil.

这是为什么?为什么 b 被赋值为 nil?由于 || 从未达到分配,我希望 b 保持未定义.如何定义但不赋值?

Why is that? Why does b get assigned nil? Since the || never reached the assignment, I would expect b to remain undefined. How can it be defined, but not assigned a value?

推荐答案

docs 解释了变量是如何创建的;据我了解,这就是解析器的工作方式:

Some of the docs explain how variables are created; the explanation as I understand it is that's just how the parser works:

局部变量在解析器遇到赋值时创建,而不是在赋值发生时创建:

The local variable is created when the parser encounters the assignment, not when the assignment occurs:

a = 0 if false # does not assign to a
p local_variables # prints [:a]
p a # prints nil

您可以看到其他示例:

b = true if false # b is nil
"test" || c = true # c is nil

还有其他人没有被分配:

And others it doesn't get assigned:

puts d if false # d generates a NameError

这篇关于为什么ruby即使从不执行变量赋值代码也要定义变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-28 07:18:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1169752.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   也要   赋值   定义   代码

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!