Instance and Local Variables
Learn the difference between instance and local variables.
We'll cover the following...
Instance variables
A careful reader would have already noticed the unknown prefix @
before the variable name. In Ruby, we can’t access variables out of the scope of the current method. The only exception is in the case of instance variables, which we’ll cover later. For example, the following Ruby code won’t be executed and will produce an error:
Press + to interact
# Error in codex = 123def print_xputs xendprint_x
The error message is: undefined local variable or method 'x' for main:Object (NameError)
. But, what is main?
It turns out that any program in Ruby is wrapped by the main
class. This is proven when we run the following program: