Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does ruby keep track of variables [duplicate]

Tags:

ruby

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?

like image 420
Rahul Tapali Avatar asked Oct 22 '22 04:10

Rahul Tapali


1 Answers

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

like image 96
Arup Rakshit Avatar answered Nov 26 '22 13:11

Arup Rakshit