`defined?` and `unless` not working as expected

懵懂的女人 提交于 2019-12-01 15:36:35

This is one of the only moments in Ruby I would call actual WTFs.

You have to use

unless defined? var
  var = :value
end

With the postfix syntax, the interpreter will internally nil-ify the value so it can reason about the variable, thus making it defined before the check is done:

# Doesn't print anything
unless defined?(foo) and (p(foo) or true)
  foo = :value
end

# Prints nil
bar = :value unless defined?(bar) and (p(bar) or true)
sawa

Local variables are defined (as nil) at the point they are parsed. Definition of var2 precedes the condition. That makes var2 defined even when if the assignment is not executed. Then, the condition evaluates that var2 is defined, which retains the value nil for var2.

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