• missing xbfish.com image

Tag Archives: ruby class

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

Instance & Class Method in Ruby

Consider the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Animal
 
    def self.haha #Class method
        puts "hello"
    end
 
    def haha #instance method
        puts "bark"
    end
 
end
 
dog = Animal.new()
dog.haha
 
Animal::haha #Calling class method

Result:

1
2
bark
hello

Writing Class, Methods in Ruby

Thanks to Xiao Ming for enlighting me.

Some examples as shown below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Human
    MY_NAME = "Willie" #This is a constant
    attr_accessor :name #Defining get, set method for variable name
 
    def initialize(name)
        @name = name
    end
 
    def getpet
        puts @pet
    end
 
    def setpet=(pet)
        @pet = pet
    end
end
 
haha = Human.new('willie')
puts haha.name
 
hehe = Human.new('mingen')
puts hehe.name
hehe.setpet = 'cat'
hehe.getpet

Output of the above codes will be:

1
2
3
Willie
mingen
cat

More information can also be look @ here: http://rubylearning.com/satishtalim/writing_our_own_class_in_ruby.html

Thanks Ming en-chan!