First of all, look at their relationship.
- IRB (main):100:0> String.class
- = = Class
- IRB (main):101:0> String.class.superclass
- = Module
- IRB (main):102:0> String.class.superclass.superclass
- = = Object
Class < Module < Object
1. Class can only be inherited, but may contain more than one module
Module AA
def aa.prints1 (str)
Print "A:" +str
End
End
Module BB
def bb.prints2 (str)
Print "B:" +str
End
End
Class CC
Include AA
Aa.prints1 ("AA")
Include BB
Bb.prints2 ("BB")
End
2, the module is similar to the C # interface, including some common interface methods, can not be instantiated
Class to invoke the module in two ways
A.RB the module name before the method. The method name (AA.PRINTS1), which can be called directly in its reference class Aa.prints1
Module AA
def aa.prints1 (str)
Print "A:" +str
End
End
B.RB If you do not add a module name, you need to include the include BB in its reference class, which is equivalent to inheriting the method, and then you can call the PRINTS2 directly.
Module BB
def prints2 (str)
Print "B:" +str
End
End
ruby-Modules and Classes