本文介绍了为什么我可以引用从未运行过的 if/unless/case 语句之外的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么下面的代码没有报错?

Why does the following code not throw an error?

if false
  x = 0
end

x  #=> nil

而以下确实会引发错误:

Whereas the following does throw an error:

y  # NameError: undefined local variable or method `y' for main:Object

同样的事情发生在 unless &case 语句.

The same thing happens with unless & case statements.

推荐答案

这是因为 Ruby 解析器的工作方式.变量由解析器定义,解析器逐行遍历代码,无论是否实际执行.

It's because of how the Ruby parser works. Variables are defined by the parser, which walks through the code line-by-line, regardless of whether it will actually be executed.

一旦解析器看到x =,它就会在当前范围内定义局部变量x(值为nil).由于 if/unless/case/for/while 不创建新的作用域,x 被定义并且在代码块之外可用.并且由于内部块永远不会被评估为条件为假,x 没有分配给(因此是 nil).

Once the parser sees x =, it defines the local variable x (with value nil) henceforth in the current scope. Since if/unless/case/for/while do not create a new scope, x is defined and available outside the code block. And since the inner block is never evaluated as the conditional is false, x is not assigned to (and is thus nil).

这是一个类似的例子:

defined?(x) and x = 0
x  #=> nil

这篇关于为什么我可以引用从未运行过的 if/unless/case 语句之外的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 00:16