且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Ruby模块可以被描述为单例类吗?

更新时间:2023-11-13 14:28:34

A ruby class is a module you can make instances of. Like a class, a module can have methods, but you cannot make an instance of a module. That's the only difference between them.

In practice, modules are commonly used for:

  • Name spaces
  • Mixins
  • To hold functions

Name Space

Here's an example of a module used as a name space:

module MyLib
  class Foo
  end
  class Bar
  end
end

The full name of these classes is MyLib::Foo and MyLib::Bar. Because they are contained in a namespace (which presumably is unique), the names Foo and Bar cannot conflict with a Foo or Bar defined in your program or in another library.

Mixin

Here's a module used as a mix-in:

module Mixin
  def foo
    puts "foo"
  end
end

Since you can't make an instance of the Mixin module, you get access to foo by including (mixing in) the module:

class MyClass
  include Mixin
end

MyClass.new.foo    # => foo

Functions

Like a class, a module can hold functions that do not operate on any instance. To do that, you define class methods in the module:

module SomeFunctions
  def self.foo
    puts "foo"
  end
end

A class method defined in a module is just like a class method defined in a class. To call it:

SomeFunctions.foo    # => foo

上一篇 : :iPhone内存警告和崩溃-但仪器显示内存不足下一篇 : 如何处理laravel 5中的私人图像?

相关阅读

推荐文章