开发者

Ruby variable initialisation

开发者 https://www.devze.com 2023-02-13 02:44 出处:网络
In the following code there is an execution path where \"bar\" is not set before it is tested, is开发者_StackOverflow doing this safe in Ruby? will \"bar\" have a default initialisation?

In the following code there is an execution path where "bar" is not set before it is tested, is开发者_StackOverflow doing this safe in Ruby? will "bar" have a default initialisation?

if foo
  bar = true
end

if bar
  puts "true"
end


Yes

Yes, it is safe, in the sense that the worst that can happen when an uninitialized local is referenced is that a NameError exception will be raised.

Yours is a bit of a special-case, actually. Since the parser will have seen bar before it is referenced, then the method will not raise NameError, even if foo is false, but rather the value of bar will be nil.

0

精彩评论

暂无评论...
验证码 换一张
取 消