Scope can be defined as the accessibility of a variable.
Say for example, in every office, there is a restricted area where only a few people have access.
Similarly, in Ruby, the variables also have some access restrictions. The variables that are defined inside a Method, cannot be accessed outside of it.
def func() x = 5 end func() puts x
Now, the program execution starts from the fourth line.
And the Method func() is called.
func()
And the Method execution begins.
def func() x = 5 end
And initialised the variable x with 5 inside the Method func().
x = 5
Then we come to the print statement,
puts x
And end up with an error as output,
This is because the variable x is not accessable outside the Method. And that is called as Local Scope.
There are five types of scope of the Variable that Ruby Supports:
For now, we will be understanding the Local and Global Scope. Class and Instance Scope would be explained in a separate tutorial.
Let us understand Local scope first.
The variables that are declared inside a Method, can only be accessed inside the Method and is local to that Method. That is called the Local Scope of a variable.
Say for example, if there are two Methods, first_func() and second_func().
def first_func() x = 5 puts "The variable x is not accesible outside the first_func()") end def second_func() y = 7 puts "The variable y is not accesible outside the second_func()") end first_func() second_func()
So, we have declared two Methods, first_func(),
def first_func() x = 5 puts "The variable x is not accesible outside the first_func()") end
And second_func().
def second_func() y = 7 puts "The variable y is not accesible outside the second_func()") end
And we have two variables, x and y.
While x is declared inside the Method first_func() and is local to the first_func() and cannot be accessed outside it.
Similarly, y is declared inside the Method second_func() and is local to the second_func() and cannot be accessed outside it.
Similarly, let us look at the other example, where the variable is declared outside the method.
x = 5 def func() puts "Inside the Method #{x}" end func() puts "Outside the Method #{x}"
So, we ended up with an error, because the variable x is defined outside the method func() and it cannot be accessed inside the method func().
def func() puts "Inside the Method #{x}" end
Let us fix the above example with a Global Variable
The variables that can be accessed throughout the program is said to be in Global Scope. The variables needs to be declared using $ at the beginning.
Let us see in the below example :
$x = 5 def func() puts "Inside the Method #{$x}" end func() puts "Outside the Method #{$x}"
So, in the above example, we have declared a variable $x, outside the Method and initialised with 5.
$x = 5
Now, since the variable name starts with $, it is treated as a Global variable. And can be accessed throughout the program.