I am confused with the way Ruby keeps track of variables. For example:
case 1:
    if true
       a
    end
will give you an error saying undefined local variable or method a.
case 2:
    if false
      a
    end
    a
will give you same the error for the second a, not for the first a.
case 3:
    if false
      a=2
    end
    a  #=> nil
    defined? a  #=> 'local-variable'
If you compare case 2 and case 3, in case 2 it ignored the error first a. I think its because of ruby's execution path has not reached the variable a due to false in condition. Same thing when I do with assignment in case 3. It gives me variable a defined but with nil value. Can someone explain the way it works?
In parse time if Ruby found any assignment such a=2,then local variable is created at that moment.It does not matter if you put in inside of any false conditional expression or not. Otherwise a legitimate error will be thrown as undefined local variable or method a,if you try to use the variable such as a here,before it's creation with the assignment(=) operator.
Look Confusion with the assignment operation inside the fallacy if block
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With