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。

ruby 学习笔记(1) 初识语法
单从技术而言,ruby本身确实很爽,令程序员的工作变得轻松有趣!下面的代码演示了如何找出100以内的素数:usingSystem;namespaceMersenne{classProgram{staticvoidMa

ruby 学习笔记(2) 类的基本使用
ruby语言跟c#的一些重要差别在于:1.ruby是动态语言,c#是静态语言--即对象在new出来以后,ruby还可以动态给对象实例添加一些属性或方法(javascript也是如

RUBY 新手教程 跟我一起学ruby
跟我一起学rubyByTiger注:本教程转载自在游戏先行者论坛,版权属于作者Tiger。第一篇第二篇第一篇自序从今天起我就要开始学Ruby了。怎么样,没见吧?