What Is Scope?

Scope refers to the reach or visibility of variables. In the object-oriented world, scope is very important. There are five types of variables/constant, each with varying levels of scope.

The different variable scopes are (in order of highest to lowest level of scope):

  • global variables
  • constants
  • class variables
  • instance variables
  • local variables

In objected-oriented design, you want classes and methods to have only single responsibilities. We don’t want to expose everything to everything. It would be a tangled mess to have all variables and methods available to all objects. This also creates a lot of dependencies. When you change one part of the code, you may need to change ten other parts of the code if they are all depending on the code that you are changing, creating a rippling effect. Using correct variable scopes to only expose what is needed helps reduce this problem.

Besides restricting access to other components of the code, scopes also keep the name space open. Since the variable is limited to its scope and is non-existent outside of it, you don’t have to worry about creating a variable with the same name and accidentally overwriting the previous assignment.

Let’s talk about each variable scope in more detail

Global Variables

Global variables have a global scope. They are available anywhere in the program. It is defined and called with a $ in front of the name (i.e. $global_variable = "I am a global variable").

Try not to use global variables unless it is absolutely necessary. There is almost always a way to substitute using global variables with something else. It is used often in functional programming, but is counter-intuitive to object-oriented programming (OOP) because it is doing exactly what OOP is designed to get rid of. Relying on global variables causes the program to become less flexible and harder to make changes to in the future. In OOP, each object should only expose what is needed; nothing more and nothing less (only expose what it does, not how it does it).

Constants

Constants also have a global scope. They start with a capital letter. The Ruby convention is to write it with in all caps and underscore (i.e. CONSTANT = "I am a constant"). If they are called from self, you only need to write the name of the constant, like local variables and methods. If you are calling from outside of self, you can still access it if you know the path of the block that defined the constant and :: (i.e. Math::PI).

Constants are not meant to be changed, but Ruby will allow it. If you choose to change a constant, Ruby will give you a warning and then make the change right afterwards.

Local Variables

Let’s jump to local variables before we talk about class and instance variables. If you’ve played with Ruby, then you’re probably already familiar with it. Local variables have a local scope and they start with a lowercase letter (i.e. local_variable = "I am a local variable"). Local variables are the most often used variables and are limited to the specific block it’s in and the blocks inside that block. They can’t be access from anywhere outside of the block.

For example:

class Destination
  def dest_1
    x = "Barcelona"
    puts x
  end
  def dest_2
    puts x
  end
end

trip = Destination.new 
trip.dest_1 # => "Barcelona"
trip.dest_2 # => undefined local variable or method `x' for #<Destination:0x007fe284058ae8> (NameError)

Or:

trip = ["Barcelona","Rome","Amsterdam"]
trip.each { |city| x = city; print x } # => BarcelonaRomeAmsterdam
print x # => undefined local variable or method `x' for main:Object (NameError)

As you can see, when the local variable is called outside of its block (in the first example, the Destination#dest_1 method block, and in the second example, the .each iterator block), it will create an error. Since the variable is out of scope, it does not exist in the block from which it is called upon.

Now, lets look at this example:

trip = ["Barcelona","Rome","Amsterdam"]
x = []
trip.each { |city| x = city; print x } # => "BarcelonaRomeAmsterdam"
p x # => "Amsterdam"

Something interested happens here. Notice how the last line now prints "Amsterdam", even though that was assigned inside the .each iterator block. Since x was first defined outside of the .each iterator block, the scope of the variable has changed. Remember what I said earlier: the scope of a local variable is limited to its block and the blocks within that block.

Instance Variables

Instance variables are only accessible to each specific instance. They begin with a @ symbol in front of the name. They are written inside instance methods and can be shared by all instance methods in that class. Since the scope of instance variables are restricted to each instance, different instances can have different values assigned to these variables.

Take this, for example:

class Destination
  def initialize(city)
    @city = city
  end
  def print_city
    puts @city
  end
end

trip_1 = Destination.new("Barcelona") 
trip_2 = Destination.new("Rome")
trip_1.print_city # => "Barcelona"
trip_2.print_city # => "Rome"

There are two things to note here. First, notice how @city is assigned in the Destination#initialize method and the assignment is still available in a different method, Destination#print_city (as evidenced by what the last 2 lines printed). The second thing to note is that @city for trip_1 is different from the @city for trip_2. Instance variables are the second most used variables in Ruby.

Class Variables

Class variables are accessible by the class and all instances of that class, so they have a wider scope than instance variables, but not as much as global variables. These variables have a @@ symbol in front of its name. They are often used if the class or any instance of the class will need to use it.

For example:

class Destination
  @@total_avail_cities = 0
  def initialize(city)
    @city = city
    @@total_avail_cities += 1
  end
  def print_total
    puts @@total_avail_cities
  end
end

trip_1 = Destination.new("Barcelona")
trip_1.print_total # => 1

trip_2 = Destination.new("Rome")
trip_2.print_total # => 2

Every time a new destination is initialized, it adds a count to @@total_avail_cities. Notice that even though trip_2 is a separate instance from trip_1, it still print 2.

Class variables are also avoided unless it is necessary. Similarly to global variables, not realizing its scope can be detrimental to your problem.

Here is an example:

class Destination
  def initialize(city)
    @@city = city
  end
  def print_city
    puts @@city
  end
end

trip_1 = Destination.new("Barcelona")
trip_2 = Destination.new("Rome")
trip_1.print_city # => "Rome"
trip_2.print_city# => "Rome"

Notice how both calls to print @@city returned "Rome". That is because the second instance changed the value of @@city when it was initialized, which carries over to all instances in that class. Be careful when using class variables and only use them when absolutely necessary.

Summary

Ruby has different types of variables that have varying levels of scope. The bigger the scope, the more careful you should be when using it. In object-oriented design, you only want what is absolutely needed to be accessible by others to make your program work, so don’t expose anything in an object that isn’t needed by others. Keep the scope in mind and choose which variables to use accordingly.

This blog has been initially published on tonymai.github.io.