Array
, Hash
, etc) assigned to a class constant
can be used as a class variable.
class Foo
F = [0]
def foo
F[0] += 1
print F[0], "\n"
end
end
class Foo
@a = 123 # (1)
def foo
p @a # (2) ... nil not 123
end
end
(1) is a class instance variable, and (2) is an ordinary instance
variable. (2) belongs to an instance of the class Foo
, and
(1) belongs to the class object Foo
, which is an instance of
Class
class.
nil
.
foo = Foo.new
def foo.hello
print "Hello\n"
end
foo.hello
It is useful when you want to add a method to an object but hesitate
to define a new subclass.
Foo
which is an instance of
Class
.
class Foo
def Foo.test
print "this is foo\n"
end
end
It is invoked this way.
Foo.test
This is a class method. Methods which are defined in Class
can
be used as class methods for every class.
class Foo
def hello
print "hello.\n"
end
end
foo = Foo.new
foo.hello
# -> hello.
class << foo
attr :name, TRUE
def hello
print "hello. I'm ", @name, ".\n"
end
end
foo.name = "Tom"
foo.hello
# -> hello. I'm Tom.
Wow, we can add anything to an object.
private_class_method
?
class Foo
...
end
class << Foo
def class_method
print "class method\n"
end
private :class_method
end
Foo.class_method " # -> Error
There are two ways in defining a singleton method, one is to define
in a singleton class, and the other is to define directly using the
form def obj.method.
Math.sqrt(2)
Or can be used with include
.
include Math
sqrt(2)
To make a method a module function, you invoke module_function method.
module_function :method_name
load
and require
?
*.rb
) is loaded and executed in load
.
require
d, *.o
file is also looked for. An already
require
d file is never loaded again.
include
and extend
?
include
is used to include a module to a class/module, and methods
in the module are called in function-style. extend
is used to
include a module to an object(instance), and methods in the module
become singleton methods of the object.
self
mean?
self
means the object itself to which a method is applied.
A function form method call implies self
as the receiver.