【问题标题】:Why does ruby define variables even if it never executes the variable assignment code?为什么 ruby​​ 定义变量,即使它从不执行变量赋值代码?
【发布时间】:2019-06-09 21:17:56
【问题描述】:

给定以下代码:

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

这是为什么呢?为什么b 被分配nil?由于|| 从未完成分配,我希望b 保持未定义。如何定义它,但没有赋值?

【问题讨论】:

    标签: ruby variable-assignment


    【解决方案1】:

    一些docs 解释了变量是如何创建的;据我了解,解释器就是这样工作的:

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

    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
    

    还有其他没有被分配的:

    puts d if false # d generates a NameError
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-08
      • 2021-09-14
      相关资源
      最近更新 更多