• missing xbfish.com image

Instance & Class Method in Ruby

missing xbfish.com image

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

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