• missing xbfish.com image

Module and Class in Ruby

missing xbfish.com image

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

One comment

  • December 12, 2008 - 2:44 am | Permalink

    You have seen the light haha

  • Leave a Reply

    Your email address will not be published. Required fields are marked *

    *

    You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">

    Spam protection by WP Captcha-Free