1. 程式人生 > >ruby基礎知識之 class&module

ruby基礎知識之 class&module

end 技術 方法 sso img 字母 ruby 分享 access

以下分別介紹了class方法和module方法,還有最簡單的def方法。

其中module和class的區別下面會說,這裏首先聲明,def定義的方法,需要定義對象後才能調用,而class和module都能隨意進入。

class方法

ruby裏的方法分為:類方法和實例方法

類方法:通過類名直接調用的方法

可以寫的形式一般是3類:

第一種:

class Fo
  def self.bar
    p "aa"
  end
end

第二種:

class Foo
  class << self

    def bar
       p "bb"

    end

  end
end

第三種:
class Fooo; end
  def Fooo.bar
  end

調用的時候:直接Foo.bar 這樣調用即可。

實例方法:通過對象調用的方法

可以寫成的形式也有3種:

第一種:

class Foo
  def baz
    p "mm"
  end
end

第二種:

class Foo
  attr accessor :baz
  end
foo = Foo.new
foo.baz = "instance method"

第三種:這種方法只針對foo這一個對象有效,稱為單例方法,函數範圍很小

class Foo; end
foo = Foo.new
def foo.baz
  p "instance method"
end

調用實例方法的時候,一定要先new一個對象出來

module(模塊)方法

提前聲明:module方法是ruby語言特有的,它是一個命名空間,避免定義了相同名稱的函數或變量導致的沖突。

module也分為module實例方法和module類方法,它的寫法其實與類方法是一毛一樣的。比如:

技術分享圖片

上面這段代碼就是一個模塊類方法,特點是在定義方法和調用方法的時候都在前面加上了所在module的名字,這樣定義的函數就叫module method 。

在定義方法名稱的時候,我們不加module name,這樣定義出來的方法就叫模塊實例方法(module instance method),這種方法就是實例方法,只能被mixin到某個class中被引用。

module與class的區別:

1、module不能實例化,即module為實例方法的module時,它不能被自己引用,需要利用include方法引用到class中;

2、module不能繼承,而class可以

常量定義:凡是首字母大寫的,都是常量,包括class和module都是,常量在調用的時候用::

調用規則:

類調用用::或者.

實例調用只能用.

所以為了區分,一般類調用我們都用::

ruby基礎知識之 class&module