Ruby: public, protected 與 private

李威辰
4 min readApr 26, 2018

--

在Ruby專案裡面我們常常可以看到private的出現,那private到底什麼時候用,什麼情況下不能用呢?而方法只要沒有特別標記的話都是public protected比較少見,用法跟private有明顯的差異。本篇文章簡單說明一下這三個方法的區別。

假設我們從一個class實例化一個instance,public實體方法(instance method)不管在class內外都可以使用。

class Example
def public_method_a
puts "public method from #{self.class}"
end

def public_method_b
public_method_a
end
end
example = Example.new
example.public_method_a # public method from Example
example.public_method_b # public method from Example

而如果是private方法的話,就沒辦法在外部呼叫這個方法,但一樣可以在內部呼叫。

class Example
def public_method
private_method
end

private

def private_method
puts "private method from #{self.class}"
end
end
example = Example.new
example.public_method # private method from Example
example.private_method # NoMethodError

值得注意的一點是,就算是繼承的類別也可以在子類別的內部直接呼叫父類別的private方法。

class Example
def public_method
private_method
end

private

def private_method
puts "private method from #{self.class}"
end
end
class SonOfExample < Example
def public_method_of_son
private_method
end
end
son_of_example = SonOfExample.new
son_of_example.public_method_of_son # private method from SonOfExample

protected方法跟private方法都一樣不能在外部呼叫

class Example
def public_method
protected_method
end

protected

def protected_method
puts "protected method from #{self.class}"
end
end
example = Example.new
example.public_method # protected method from Example
example.protected_method # NoMethodError

那protected跟private方法的差別到底在哪邊呢?答案是private前面不能夠有呼叫的對象,而protected可以。

class Example
def public_method_a
self.private_method
end

def public_method_b
self.protected_method
end

protected

def protected_method
puts "protected method from #{self.class}"
end

private

def private_method
puts "private method from #{self.class}"
end
end
example = Example.new
example.public_method_b # protected method from Example
example.public_method_a # NoMethodError

由上面這個例子可以看到,就算呼叫方法的receiver是self也沒辦法從內部去呼叫private方法,而protected方法可以。

做個總結:

  1. 三種方法都可以在class內部被呼叫。
  2. 只有public方法能在外部被呼叫。
  3. 在內部呼叫private方法的時候不能夠有receiver,而protected方法則沒有這種限制。

--

--