Object-Oriented Programming

Variable Scope

February 17, 2015

So we have been working with Ruby for awhile now and we need to talk about variable scope. Basically there are different types of variables, and each one has a different level of scope or accessibility. Ruby has four types of variable scope, and one constant type. The variable scope are global, instance, local and class. The constant type is called a constant.

Lets talk about a constant first. A constant begins with [A-Z], has to be a capital letter. These variables should be constant. Ruby allows you to change these value once they have been defined, but will send a warning message. It may be best practice to just think of constant as always being the same value, so they are constantly staying the same.

Global variables are accessible for anywhere in the Ruby program. It doesn't matter where you have declared them, if its global you can access it. Global variables need to start with the $ sign. For example $hello = "hello world". Use of global variables are discouraged because not only can you access them from the program you define them in but also anywhere in the application. Can be useful but only use them when needed.

Class variables is a variable that is shared in all instances of that class. It is like a global variable that it can be accessed throughout an entire class but it is constrained to that given class. Class variables are declared using two @ characters - @@. Here is an example, @@hello = "hello world.". The main thing to remember is that class variables are shared between all instance of that variable. If at any point in the class we change the value of the class variable, the new value is set to be equal to all instances of that variable on all objects. For instance, lets say we have two object object_1 = @@variable and object_2 = @@variable. If we change what @@variable is equaled to for object_2, it would also change object_1 value.

Instance variables is what we have been using the most. It is a variable that can be accessed throughout an entire class, just like class variables, but if we change its value it won't change all instance of that variable. It will only change the variable value for the given object. Instance variables are defined with one @. An example would be @hello = "hello world".

And lastly local variables. This variables can only be used in the code where they are declared. If you declare a local variable in one method, you won't be able to access it in a different method. It is a very useful variable, because you can use the same variable name in multiple places and not run into errors. It not the best practice to use the same variable name but you need to use it in just a block it is useful. Local variables being with [a-z] (has to be lowercase) or _.