Ruby 之 class 中的 private、 protected、public

所属分类: 脚本专栏 / ruby专题 阅读数: 781
收藏 0 赞 0 分享
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。
更多精彩内容其他人还在看

解析 ruby 全局变量

解析 ruby 全局变量
收藏 0 赞 0 分享

ruby 实变量

ruby 实变量
收藏 0 赞 0 分享

ruby 局部变量

ruby 局部变量
收藏 0 赞 0 分享

ruby 类常量 解析

ruby 类常量 解析
收藏 0 赞 0 分享

ruby 异常处理:rescue

ruby 异常处理:rescue
收藏 0 赞 0 分享

ruby 异常处理:ensure

ruby 异常处理:ensure
收藏 0 赞 0 分享

ruby 存取器 概念

ruby 存取器 概念
收藏 0 赞 0 分享

ruby 对象的初始化 方法

ruby 对象的初始化 方法
收藏 0 赞 0 分享

ruby 杂项

ruby 杂项
收藏 0 赞 0 分享

初步了解一下什么是ruby

了解下什么是ruby,希望学习ruby的朋友了解下
收藏 0 赞 0 分享
查看更多