What is a module? Can you tell me the difference between classes and modules?

Technology CommunityCategory: RubyWhat is a module? Can you tell me the difference between classes and modules?
VietMX Staff asked 3 years ago

Modules serve as a mechanism for namespaces.

module ANamespace
  class AClass
    def initialize
      puts "Another object, coming right up!"
    end
  end
end

ANamespace::AClass.new
 #=> Another object, coming right up!

Also, modules provide as a mechanism for multiple inheritance via mix-ins and cannot be instantiated like classes can.

module AMixIn
  def who_am_i?
    puts "An existentialist, that's who."
  end
end

# String is already the parent class
class DeepString < String
  # extend adds instance methods from AMixIn as class methods
  extend AMixIn
end

DeepString.who_am_i?
 #=> An existentialist, that's who.

AMixIn.new
 #=> NoMethodError: undefined method ‘new’ for AMixIn:Module