Showing posts with label ruby module. Show all posts
Showing posts with label ruby module. Show all posts

Monday, July 16, 2012

Modules in Ruby - an overview

We can define any number of methods in a module. It simply holds all the defined methods and we can include/extend it in any class.
If you want to use all module methods access by an instance then include the module in that class.
If you want to use all module methods access by an class then extend the module in that class.
module Foo
  def foo
    puts 'foo called!'
  end
end

class Bar
  include Foo
end

Bar.new.foo # foo called!
Bar.foo # NoMethodError: undefined method ‘foo’ for Bar:Class

class Baz
  extend Foo
end

Baz.foo # foo called!
Baz.new.foo # NoMethodError: undefined method ‘foo’ for #


Hope this helps. Happy learning & coding :)

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).