Ruby Variable Scope

From Techotopia
Revision as of 18:44, 15 November 2007 by Neil (Talk | contribs) (What is Variable Scope?)

Jump to: navigation, search

Now that we have covered the basics of variables in Ruby the next task is to explain Ruby variable scope.

What is Variable Scope?

Scope defines where in a program a variable is accessible. Ruby has four types of variable scope, local, global, instance and class. In addition, Ruby has one constant type. Each variable type is declared by using a special character at the start of the variable name as outlined in the following table.

Name Begins WithVariable Scope
$ A global variable
@ An instance variable
[a-z] or _ A local variable
[A-Z] A constant
@@A class variable

In addition, Ruby has two pseudo-variables which cannot be assigned values. These are nil which is assigned to uninitialized variables and self which refers to the currently executing object.