未评估行的Ruby变量赋值

时间:2017-12-04 02:14:02

标签: ruby

最近我发现Ruby中的非评估行仍然会将nil分配给变量。

2.3.4 (main):0 > defined? this_never_seen_variable_before
=> nil
2.3.4 (main):0 > this_never_seen_variable_before = "value" if false
=> nil
2.3.4 (main):0 > defined? this_never_seen_variable_before
=> "local-variable"
2.3.4 (main):0 >
2.3.4 (main):0 > this_never_seen_variable_before_2
   NameError: undefined local variable or method `this_never_seen_variable_before_2' for main:Object
from (pry):119:in `<main>'
2.3.4 (main):0 > this_never_seen_variable_before_2 = "value" if false
=> nil
2.3.4 (main):0 > this_never_seen_variable_before_2
=> nil
2.3.4 (main):0 >

有人会有更多相关信息吗?

1 个答案:

答案 0 :(得分:2)

在运行Ruby代码之前,必须首先对其进行解析,并且在此阶段,您所遇到的行为源自您的行为。

当解析器扫描代码时,无论何时遇到声明(foo = 'something'),它都会通过将其值设置为nil来为该变量分配空间。是否在代码的上下文中实际执行了变量声明是无关紧要的。例如:

if false
  foo = 42
end

p foo
#=> nil

在上面的代码中,永远不会声明逻辑foo,但是在解析代码时,Ruby会识别并分配内存中的空间。

希望这有帮助!