Why does ruby define variables even if it never executes the variable assignment code?

依然范特西╮ 提交于 2019-12-06 00:03:35

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

You can see other examples of this:

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!