Ruby has four types of variable scope,
Name Begins With | Variable Scope |
---|---|
$ | A global variable |
@ | An instance variable |
[a-z] or _ | A local variable |
[A-Z] | A constant |
@@ | A class variable |
Detecting the Scope of a Ruby Variable
x = 10 => 10 defined? x => "local-variable" $x = 10 => 10 defined? $x => "global-variable"
Ruby Class Variables
A class variable is a variable that is shared amongst all instances of a class.
Class variables must be initialized at creation time.
@@total = 0
Another way of thinking of thinking of class variables is as global variables within the context of a single class.
Ruby Instance Variables
Instance variables are similar to Class variables except that their values are local to specific instances of an object.
----------------------------------------------------------------------------------------------------------------
No comments:
Post a Comment