当前位置: 首页 > 图文教程 > 脚本技术 > Ruby > Ruby 之 class 中的 private、 protected、public

Ruby
Rails link_to 详解
ruby 小脚本搞定CVS服务器更换后checkout下来的工程迁移
Ruby 魔法 学习笔记之一
Ruby self在不同环境的含义
ruby 程序的执行顺序
ruby on rails 代码技巧
ruby 标准类型总结
ruby 去掉文件里重复的行
Ruby 取得指定月日期数的方法
Ruby 中关于日文转UTF-8及半角全角转换的技巧
比较不错的关于ruby的电子书下载地址集合
二十分钟 教你Ruby快速入门 图文教程
Terry七月Ruby读书笔记(比较详细)
Ruby rails 页面跳转(render和redirect_to)
Ruby 之 class 中的 private、 protected、public

Ruby 之 class 中的 private、 protected、public


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2010-01-10   浏览: 335 ::
收藏到网摘: n/a

Ruby 之 class 中的 private、 protected、public Private
private 函数只能 在本类和子类的 上下文中调用,且只能通过self访问。
这个意思就是:private函数,只能在本对象内部访问到。
对象实例变量(@)的访问权限就是 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) #错误 in `test_other': private method `test' called for #<AccessTest:0x292c14> (NoMethodError)

Protected
protect 函数只能 在本类和子类的 上下文中调用,但可以使用 other_object.function的形式。(这跟 C++ 的 private 模式等同)
这个的关键是 protected函数可以在同类(含子类)的其它对象的内部中使用。
# Now make 'test' protect
class AccessTest
protected:test
end
p t1.test_other(t2) # other object test private
Public
public 函数可以在任何地方调用。成员函数和常量的默认访问权限就是public。