作为参数传递时,未定义的局部变量强制为nil

Tra*_*vis 3 ruby

我错误地编写了一个方法,该方法将一个变量赋值给方法调用的返回值,该方法调用在以前未定义时将参数传递给参数.我很想知道这是Ruby中的错误,还是实际的预期行为?

RUBY_VERSION
#=> "2.2.4"

def red(arg)
  arg
end

# this is expected since blue is not defined
blue
NameError: undefined local variable or method 'blue' for main:Object
from (pry):8:in '__pry__'

red(blue)
NameError: undefined local variable or method 'blue' for main:Object
from (pry):4:in '__pry__'

# here's the weird part
blue = red(blue)
#=> nil

blue
#=> nil
Run Code Online (Sandbox Code Playgroud)

use*_*234 5

来自David Flanagan的"Ruby Programming Language":

如果标识符已经看到任何先前对变量的赋值,则Ruby将标识符视为局部变量.即使从未执行过该分配,它也会这样做.

这意味着即使在执行任何代码之前,Ruby解析器也会隐式声明变量.一旦ruby看到=运算符,它会立即生成一个名为yellow默认值的新变量nil.然后,当执行该语句时,对该变量的每个引用都共享它的默认值.

本书接着展示了一个类似的,也许是令人惊讶的ruby变量声明行为的例子,类似于:

>> x               # NameError: undefined local variable or method `x'
>> x = 0 if false  # parsed, but never executed
>> p x             # displays nil
Run Code Online (Sandbox Code Playgroud)

这段代码的重要性在于表明变量是在解析代码后立即声明的,并且由于您的两个引用yellow发生在同一行上,因此必须先解析黄色的赋值,然后在它作为参数传递之前声明至green