Difference between revisions of "Ruby Variable Scope"

From Techotopia
Jump to: navigation, search
(What is Variable Scope?)
(What is Variable Scope?)
Line 8: Line 8:
 
<tr style="background:#efefef;">
 
<tr style="background:#efefef;">
 
<th>Name Begins With<th>Variable Scope</th>
 
<th>Name Begins With<th>Variable Scope</th>
<tr><td><code>$</code> </td><td> a global variable </td></tr>
+
<tr><td><code>$</code> </td><td>A global variable </td></tr>
 
<tr><td>
 
<tr><td>
 
<code>@</code> </td><td> An instance variable </td></tr>
 
<code>@</code> </td><td> An instance variable </td></tr>
Line 16: Line 16:
 
<code>[A-Z]</code> </td><td>A constant</td></tr>
 
<code>[A-Z]</code> </td><td>A constant</td></tr>
 
<tr><td>
 
<tr><td>
<code>@@</code></td><td>A class variable</td>/tr></table>
+
<code>@@</code></td><td>A class variable</td></tr></table>
  
 
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.
 
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.

Revision as of 18:44, 15 November 2007

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.