Hello,
Coz Ruby’s class and module are close to Perl’s, I think it’s not hard
to understand for them.
I wrote a note below for learning them, if I’m not correct, please
point it out, thanks.
- class is defined with the keyword of “class”, module is defined
with the keyword of “module”.
for example, define a class:
class Myclass
def echo (a,b)
puts a + b
end
end
define a module:
module Mymod
def echo (a,b)
puts a+b
end
end
- If we want to call the methods in a class, need to instantiate the
class with “new” (except the class method).
If we want to call the methods in a module, need to include it
(except the module method).
call the methods in a class:
class Myclass
def echo (a,b)
puts a + b
end
end
x = Myclass.new
x.echo(“hello”,“world”)
call the methods in a module:
module Mymod
def echo (a,b)
puts a+b
end
end
include Mymod
echo “hello”,“world”
- class itself has class method, module itself has module method.
if we call a class method or a module method, won’t use “new” or
“include”.
the class method:
class Myclass
def Myclass.echo(a)
puts a
end
end
Myclass.echo(“hello world”)
the module method:
class Mymod
def Mymod.echo(a)
puts a
end
end
Mymod.echo “hello world”
- the calling and called relationship between class and module:
A module can contain methods, constants, other modules, and even
classes.
A module can inherit from another module, but it may not inherit from a
class.
As a class may include a module, it may also include modules that have
inherited other modules.
