Constants defined within a class or module may be accessed unadorned
anywhere within the class or module.
Outside the class or module, they
may be accessed using the scope operator, ``
::
'' prefixed by an
expression that returns the appropriate class or module object.
Constants defined outside any class or module may be accessed
unadorned or by using the scope operator ``
::
'' with no prefix. Constants may not
be defined in methods.
OUTER_CONST = 99
|
class Const
|
def getConst
|
CONST
|
end
|
CONST = OUTER_CONST + 1
|
end
|
Const.new.getConst
|
� |
100
|
Const::CONST
|
� |
100
|
::OUTER_CONST
|
� |
99
|
Global variables are available throughout a program. Every reference
to a particular global name returns the same object. Referencing an
uninitialized global variable returns
nil
.
Class variables are available throughout a class or module body. Class
variables must be initialized before use. A class variable is shared
among all instances of a class and is available within the class
itself.
class Song
@@count = 0
def initialize
@@count += 1
end
def Song.getCount
@@count
end
end
|
Class variables belong to the innermost enclosing class or
module. Class variables used at the top level are defined in
Object
, and behave like global variables. Class variables defined
within singleton methods belong to the receiver if the receiver is a
class or a module; otherwise, they belong to the class of the receiver.
class Holder
@@var = 99
def Holder.var=(val)
@@var = val
end
end
a = Holder.new
def a.var
@@var
end
|