Ruby 之 class 中的 private、 protected、public
更新時(shí)間:2009年11月26日 19:09:47 作者:
Ruby 之 class 中的 private、 protected、public
Private
private 函數(shù)只能 在本類和子類的 上下文中調(diào)用,且只能通過self訪問。
這個(gè)意思就是:private函數(shù),只能在本對(duì)象內(nèi)部訪問到。
對(duì)象實(shí)例變量(@)的訪問權(quán)限就是 private。
class AccessTest
def test
return “test private”
end
def test_other(other)
“other object ”+ other.test
end
end
t1 = AccessTest.new
t2 = AccessTest.new
p t1.test # => test private
p t1.test_other(t2) # => other object test private
# Now make 'test' private
class AccessTest
private :test
end
p t1.test_other(t2) #錯(cuò)誤 in `test_other': private method `test' called for #<AccessTest:0x292c14> (NoMethodError)
Protected
protect 函數(shù)只能 在本類和子類的 上下文中調(diào)用,但可以使用 other_object.function的形式。(這跟 C++ 的 private 模式等同)
這個(gè)的關(guān)鍵是 protected函數(shù)可以在同類(含子類)的其它對(duì)象的內(nèi)部中使用。
# Now make 'test' protect
class AccessTest
protected:test
end
p t1.test_other(t2) # other object test private
Public
public 函數(shù)可以在任何地方調(diào)用。成員函數(shù)和常量的默認(rèn)訪問權(quán)限就是public。
private 函數(shù)只能 在本類和子類的 上下文中調(diào)用,且只能通過self訪問。
這個(gè)意思就是:private函數(shù),只能在本對(duì)象內(nèi)部訪問到。
對(duì)象實(shí)例變量(@)的訪問權(quán)限就是 private。
復(fù)制代碼 代碼如下:
class AccessTest
def test
return “test private”
end
def test_other(other)
“other object ”+ other.test
end
end
t1 = AccessTest.new
t2 = AccessTest.new
p t1.test # => test private
p t1.test_other(t2) # => other object test private
# Now make 'test' private
class AccessTest
private :test
end
p t1.test_other(t2) #錯(cuò)誤 in `test_other': private method `test' called for #<AccessTest:0x292c14> (NoMethodError)
Protected
protect 函數(shù)只能 在本類和子類的 上下文中調(diào)用,但可以使用 other_object.function的形式。(這跟 C++ 的 private 模式等同)
這個(gè)的關(guān)鍵是 protected函數(shù)可以在同類(含子類)的其它對(duì)象的內(nèi)部中使用。
# Now make 'test' protect
class AccessTest
protected:test
end
p t1.test_other(t2) # other object test private
Public
public 函數(shù)可以在任何地方調(diào)用。成員函數(shù)和常量的默認(rèn)訪問權(quán)限就是public。
相關(guān)文章
Ruby中的方法(函數(shù))學(xué)習(xí)總結(jié)
這篇文章主要介紹了Ruby中的方法(函數(shù))學(xué)習(xí)總結(jié),本文講解了函數(shù)的命名規(guī)則、函數(shù)參數(shù)、返回值等內(nèi)容,需要的朋友可以參考下2014-11-11
openSUSE下的Ruby安裝openssl出錯(cuò)解決方法
這篇文章主要介紹了openSUSE下的Ruby安裝openssl出錯(cuò)解決方法, 本文方法同時(shí)適用類似錯(cuò)誤的其它包的安裝中,需要的朋友可以參考下2014-11-11
Ruby實(shí)現(xiàn)插入排序算法及進(jìn)階的二路插入排序代碼示例
插入排序即是把已有的有序序列從后向前掃描插入元素,數(shù)值大的向后移動(dòng),這里我們就來看一下使用Ruby實(shí)現(xiàn)插入排序算法及進(jìn)階的二路插入排序代碼示例2016-06-06
使用Ruby on Rails快速開發(fā)web應(yīng)用的教程實(shí)例
這篇文章主要介紹了使用Ruby on Rails快速開發(fā)web應(yīng)用的教程實(shí)例,本文來自于IBM官方技術(shù)文檔,需要的朋友可以參考下2015-04-04
win7安裝ruby on rails開發(fā)環(huán)境
看到很多文章都說ruby環(huán)境在windows上是非常難搭建,會(huì)出現(xiàn)各種各樣的怪問題,所以都推薦到linux和mac上安裝開發(fā)。但是我按照教程搭了下,問題也不算太多??傔^大概花費(fèi)了2個(gè)半小時(shí)左右就完成了。下面就把安裝的步驟及具體的版本記錄了一下供大家參考。2014-07-07

