Veerasundaravel's Ruby on Rails Weblog

January 23, 2009

Ruby Variable Scope

Filed under: Ruby — Tags: , , , , , , , , — Veerasundaravel @ 1:59 pm

Scope defines where in a program a variable is accessible. Ruby has four types of variable scope, local, global, instance and class.

Each variable type is declared by using a special character at the start of the variable name as follows:

$ – A global variable
@ – An instance variable
[a-z] or _ – A local variable
@@ – A class variable
[A-Z] – A constant


How to find Scope of a Ruby Variable:

You can find the scope of a ruby variable using the above mentioned special characters. However, you need to find out the scope programmatically. A useful technique to find out the scope of a variable is to use the defined? method.

x = 10
=> 10
defined? x
=> "local-variable"

@x = 10
=> 10
defined? @x
=> "instance-variable"

@@x = 10
=> 10
defined? @@x
=> "ariable"

$x = 10
=> 10
defined? $x
=> "global-variable"


Ruby Local Variables:

Local variables are local to the code construct in which they are declared. For example, a local variable declared in a method or within a loop cannot be accessed outside of that loop or method. Local variable names must begin with either an underscore or a lower case letter. For example:

total_amount = 10
_TotalAmount = 2


Ruby Instance Variables:

Instance variables are similar to Class variables except that their values are local to specific instances of an object. For example if a class contains an instance variable called @total, if one instance of the object changes the current value of @total the change is local to only the object that made the change. Other objects of the same class have their own local copies of the variable which are independent of changes made in any other objects.

Instance variables are declared in Ruby by prefixing the variable name with a single @ sign:

@total = 1


Ruby Class Variables:

A class variable is a variable that is shared amongst all instances of a class. This means that only one variable value exists for all objects instantiated from this class. This means that if one object instance changes the value of the variable, that new value will essentially change for all other object instances.

Another way of thinking of thinking of class variables is as global variables within the context of a single class.

Class variables are declared by prefixing the variable name with two @ characters (@@). Class variables must be initialized at creation time. For example:

@@total = 1


Ruby Global Variables:

Global variables in Ruby are accessible from anywhere in the Ruby program, regardless of where they are declared. Global variable names are prefixed with a dollar sign ($). For example:

$message = 'Welcome to Ruby world.'


%d bloggers like this: