Day06 - Ruby三種存取限制:Public,Protected,Private

前情提要:面試

在第五天的最後,咱們提到了一句話「相同的class的實體也沒法使用別人的singleton method」。sql

在今天,咱們把焦點放在Ruby的method,繼續瞭解存取限制:)網絡

Ruby經典面試題目#06
說明Ruby的三種存取限制。3 levels of access control for Ruby methods.測試

讓咱們用Ruby代碼分別描述三種存取:Public,Protected,Private:this

class TingsIronmanProcess
def publish
p「Hi guys,this is my IT article for today!」
endspa

protected
def mydraft
p「Hi Mentor!Please read my draft.「
endsqlite

private
def myspace
p「I'm writing secretly here!」
end
end繼承

day6 = TingsIronmanProcess.new
day6.publish # => Hi guys,this is my IT article for today!
以我本身生產第六天IT賽文章爲例,爲了防止網絡斷線,或是在IT邦寫完誤按其餘的鈕致使存盤出現問題,我一般在本機環境上編寫天天的主題。在這段時間要蒐集素材、測試代碼,這個過程可能會有不少生產上的祕密、須要刪除的錯誤等等之類的,過程艱辛不足爲外人道矣,因此放在private的myspace方法孤芳自賞就好(jxpue)。開發

等到文章接近完成度高、可讀性佳的地步,就放在protected的環境,開放一些權限給它人閱讀,例如請Ruby前輩'饅頭貓'先校稿,提供修改建議。get

因此若是在class外想要取得protected或private方法,都會出現NoMethodError錯誤:

day6.protected #=> undefined method `protected'(NoMethodError)
day6.private #=> undefined method `private'(NoMethodError)
當一切修改完畢,就能夠品嚐甜美果實,放到public區,給大衆分享個人做品啦!

以上的類別寫法能夠改爲:

class TingsIronmanProcess
def publish
p「Hi guys,this is my IT article for today!」
end

def mydraft
p「Hi Mentor!Please read my draft.「
end

def myspace
p「I'm writing secretly here!」
end

protected:mydraft
private:myspace
end
這種寫法,我以爲蠻相似於在開發Ruby on Rails項目上時常看到相似的構架,哪些套件只能在開發環境development使用,哪些在測試環境test、哪些在正式環境production使用的分組。

gem 'sqlite3',group::development
gem 'pg',group::production
若是我想把第六天的草稿send給menter看,能夠把mydraft看成參數,使用send()方法,結果以下:

day6.send(:mydraft)#=>「Hi Mentor!Please read my draft.「
甚至把文章鏈接先send給某我的看,也行:(要當心!別把不能公開的東西亂放啊!)

day6.send(:myspace)#=>「Hi guys,this is my IT article for today!
若是饅頭貓也想使用個人構架來撰寫本身的鐵人賽文章,能夠繼承個人類別:

class TingsIronmanProcess
protected
def mydraft
p「Hi Mentor!」
end

private
def myspace
p「I'm writing secretly here!」
end
end

class BaterProcess < TingsIronmanProcess
def bater_draft
mydraft
end
def bater_self_draft
self.mydraft
end
end

BaterProcess.new.bater_draft # Hi Mentor!
BaterProcess.new.bater_self_draft #Hi Mentor!
在加入繼承後的新類別,咱們引入昨天self物件能夠代替自身類別的觀念。

以繼承的類別來講,在此呼叫Protected method的方式,不管是self.mydraft或是mydraft,輸出結果都是Hi Mentor!。

但若是呼叫的是Private method myspace呢?

class BaterProcess < TingsIronmanProcess

def bater_space
myspace
end
def bater_self_space
self.myspace
end
end
若是咱們在這裏使用.self,就會出錯:

BaterProcess.new.bater_space # => I'm writing secretly here!

BaterProcess.new.bater_self_space # => private method `myspace'(NoMethodError)
龍哥的文章說到,呼叫private方法的時候,不能有明確的接收者。愛注意呀!

總結:在寫鐵人賽的文章時,我都儘量地把前幾篇的概念拿到後面來使用,增長本身觀念上的熟悉度,儘可能作到具備教育意義地環環相扣。(顯示爲八點檔連續劇製做人?)

在今天Day6這篇文章裏,咱們把次日繼承和第四天self的概念拿來測試public、protect和private存取方法(xcsjbj),也發現了:

protected:mydraft
private:myspace
:mydraft,:myspace這些冒號在前面的參數。

這究竟是什麼呢?

明天咱們就來討論符號(Symbol)吧!:)

相關文章
相關標籤/搜索