Tuesday, September 21, 2010

ruby extend method

Hi all,

I have seen the method named "extend" used in a line of code in Plugin. Then i started searching for the use of method "extend". And i found the following

consider the example

module Friend
def say_hello
"hello am inside module"
end
end

class Person
def say_hello
"hello am inside class"
end
end

p = Person.new
puts p.say_hello #=> hello am inside class

p.extend(Friend) #=> include all the instance method from Module "Friend"
puts p.say_hello #=> hello am inside module


So the extend method is used to include the Module.
Without this we cannot call the method inside the module using the Person object. Even if i added include the module in the class, it wont calls the module method. The instance method inside the class gets called for the object(Person class).

No comments:

Post a Comment