Scope of Variables
Learn scope of local and instance variables in Ruby.
We'll cover the following...
You might have noticed that we used @
, also known as the “at” sign, before the state
variable. This syntax is used to define instance variables. We already covered this a little bit in previous chapters. But in general, we have three types of variables:
Local variables
Local variables are normally defined inside of a method and not accessible from other methods. For example, the following code will produce the error because the aaa
variable isn’t defined in method m2
:
Press + to interact
# Error due to 'aaa' variableclass Foodef m1aaa = 123puts aaaenddef m2puts aaaendendfoo = Foo.newfoo.m1 # works fine, prints 123foo.m2 # won't work, variable not defined
Instance variables
Instance variables are of the particular class instance, or variables of a particular object. We can access these variables with at sign @
:
Press + to interact
# No error due to '@'class Foodef initialize@aaa = 123enddef m1puts @aaaenddef m2puts @aaaendendfoo = Foo.newfoo.m1foo.m2
Instance variables ...