3

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

if foo
  bar = true
end

if bar
  puts "true"
end

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

3 Comments

To be more explicit, if doesn't introduce a new scope in ruby. So the bar variable is introduced in the environment.
So in my above example, what would bar contain if the first conditional was bypassed?
when the foo conditional is false: nil

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.