Module vs class in ruby programming language

Modules are about providing methods that you can use across multiple classes - think about them as “libraries” (as you would see in a Rails app). Classes are about objects; modules are about functions. Class is mainly different from Module by 3 main methods: new, allocate, superclass.
The table below show you the different between them.
 ClassModule
instantiationcan be instantiatedcan not be instantiated
usageobject creationmixin facility. provide a namespace.
superclassmoduleobject
methodsclass methods and instance methodsmodule methods and instance methods
inheritanceinherits behaviour and can be base for inheritanceNo inheritance
inclusioncannot be includedcan be included in classes and modules by using the include command (includes all instance methods as instance methods in a class/module)
extensioncan not extend with extend command (only with inheritance)module can extend instance by using extend command (extends given instance with singleton methods from module)
Example codes
module A
  class B
    def initialize
      @ins_var = 1
    end
  end
end

a = A.new # undefined method new for A:Module
a = A::B.new
puts a.ins_var # 1

Nhận xét

Bài đăng phổ biến từ blog này

Chuyển biểu thức trung tố sang tiền tố và hậu tố bằng Stack

Cài đặt OpenCV trên Windows với Visual Studio 2013

HÀM THỐNG KÊ STATISTICAL TRONG EXCEL