• missing xbfish.com image

Tag Archives: difference between module and class ruby

Module and Class in Ruby

Headache, module and class is so similar. So, what’s the difference?

Consider the following piece of code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
module Willie
    NAME = "willie"
 
    def hello
        "Hello"
    end
 
    #module_function :hello
end
 
#puts Willie.hello
 
class Mingen
    include Willie
 
    def shout
        hello + " I am Ming En"
    end
end
 
xiaoming = Mingen.new()
puts xiaoming.shout

In the above example, a class can include a module and call the module method directly. Results is as below:

1
Hello I am Ming En

However, we cannot call the module method directly, it will result in an error! So, we have to make use of module_function so that the method(s) in a module can be called.

Example:

1
2
3
4
5
6
7
8
9
10
11
module Willie
    NAME = "willie"
 
    def hello
        "Hello"
    end
 
    module_function :hello
end
 
puts Willie.hello

Result:

1
Hello

Notice that calling a Module method is different from calling a Class static Method. A module object do not need to be created. Take note of the below, Module is represent as Mod and Class is represent as Class!

1
2
Mod.method #Calling Module method without instantiating
Class::method #Calling Class method without instantiating