• missing xbfish.com image

Monthly Archives: December 2008

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!