Changes

Jump to: navigation, search

Ruby Variable Scope

1,745 bytes added, 19:12, 15 November 2007
m
Ruby Global Variables
=> 17403
</pre>
 
== 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:
 
<pre>
@@total = 0
</pre>
 
== Ruby Instance Variables ==
 
Instance variables are similar to Class variables except that their values are local to specific instances of an object. For example is 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:
 
<pre>
@total = 10
</pre>
 
== Ruby Constant Scope ==
 
Ruy constants are values which, once assigned a value, should not be changed. Ruby differs from most programming languages in that it allows a constant value to be changed after it has been declared, although the interpreter will protest slightly with a warning message.
 
Constants declared within a class or module are available anywhere within the context of that class or module. Constants declared outside of a class or module are assigned global scope.

Navigation menu