2

I am bit baffled about the below behavior

if true
  foo = "true"
end

if false
  bar = "false"
end

foo # => "true"
bar # => nil
buzz # => 
# ~> -:11:in `<main>': undefined local variable or method `buzz' for main:Object (NameError)

I expect bar to throw a NameError but it does not, I actually hit this when I was playing around with some friends but nobody could give a clear explanation to this behavior, thanks in anticipation of a clear answer

bjhaid
  • 9,592
  • 2
  • 37
  • 47
  • 1
    That second one @ArupRakshit found is a much better match. – Mark Reed Nov 26 '13 at 18:29
  • this is the best answer I have found so far on the topic http://stackoverflow.com/questions/20415230/why-do-variables-get-defined-when-they-only-occur-in-unexecuted-ruby-code/20415394#answer-20415394 reveals exactly how the interpreter reads the code – bjhaid Dec 19 '13 at 14:53

1 Answers1

1

In ruby, the variables declared inside the if block have the exact same scope as the variables which are declared at the top level inside a method. Since the interpreter has gone through the line where it has seen bar, its fine with it.

noMAD
  • 7,744
  • 19
  • 56
  • 94
  • then why is assigned as nil?? – bjhaid Nov 26 '13 at 18:11
  • 1
    Because it didn't actually execute the assignment. Just compiling the assignment is enough for the interpreter to recognize `bar` as a legitimate variable name. Also, this works with no previous mention of `bar`: `bar = bar # bar is now nil` – Mark Reed Nov 26 '13 at 18:12