Modules


Collapse Content

Modules

A Module is a collection of methods and constants. Module methods may be called without creating an encapsulating object

module ModuleExample
  def foo
    'foo'
  end
end

# Including modules binds the methods to the object instance
# Extending modules binds the methods to the class instance

class Person
  include ModuleExample
end

class Book
  extend ModuleExample
end

Person.foo     # => NoMethodError: undefined method `foo' for Person:Class
Person.new.foo # => 'foo'
Book.foo       # => 'foo'
Book.new.foo   # => NoMethodError: undefined method `foo'

Including Modules II

# Callbacks when including and extending a module are executed    
module ConcernExample
  def self.included(base)
    base.extend(ClassMethods)
    base.send(:include, InstanceMethods)
  end

  module ClassMethods
    def bar
      'bar'
    end
  end

  module InstanceMethods
    def qux
      'qux'
    end
  end
end

class Something
  include ConcernExample
end

Something.bar     # => 'bar'
Something.qux     # => NoMethodError: undefined method `qux'
Something.new.bar # => NoMethodError: undefined method `bar'
Something.new.qux # => 'qux'

Challenge

Ruby's Math module contain a large number of useful functions. Call Math's sqrt function on the number 25.

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Comments

Contact Us