Variable Prefixes


Ruby Way
By Hal Fulton
Slots : 1.0
Table of Contents

Ruby variables are allowed to have special prefixes such as $, @, and @@ to indicate the scope of the variable. Regardless of the scoping prefix, variables may reference any object, just as in Python.

A global variable is prefixed with $ and is truly global, crossing all boundaries, whether inside a class, method, module, or loaded source file. There are some exceptions for built-in globals ($_ and $~). The use of $ for global variables eliminates the need for declarators such as Python's global.

An instance variable is prefixed with a single @. Using @myattribute replaces using self.myattribute in Python. (Actually, the self notation can be used in Ruby as well.) By its very nature, the instance variable can only be created and used from within the instance itself. You must use an accessor method in order to get or set the value from outside the instancerefer to any Ruby reference for a discussion of attr_accessor. Using @ for instance variables facilitates hiding, fast lookups, and exclusion from dot notation.

The class variable is prefixed with @@, and is shared only among all the instances of a class and its subclasses. An identifier starting with an uppercase letter (without a prefix) is called a constant, and is attached to a class or module namespace and the :: scope operator.

Finally, a non-capitalized variable with no prefix is a local variable. The point of assignment marks the beginning of its scope. It cannot be seen outside of a module, class, or methodand sometimes not outside of a closure (iterator block), either. This last case is a block-local variable, which only occurs if the local variable's scope started inside the closure.




The Ruby Way
The Ruby Way, Second Edition: Solutions and Techniques in Ruby Programming (2nd Edition)
ISBN: 0672328844
EAN: 2147483647
Year: 2000
Pages: 119
Authors: Hal Fulton

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: