Initializing Ruby Variables

The following code has an execution path in which "bar" is not set before testing it, makes it safe in Ruby? will the bar have default initialization?

if foo
  bar = true
end

if bar
  puts "true"
end
+3
source share
1 answer

Yes

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

You actually have a slightly special case. Since the parser will see barbefore its reference, then the method will not raise NameError, even if it foois false, but the value barwill be nil.

+7
source

Source: https://habr.com/ru/post/1794585/


All Articles