当说明“私有” /“受保护”时,实际上发生了什么?在Ruby中? [英] What actually occurs when stating "private"/"protected" in Ruby?
问题描述
在Ruby类定义中声明 private
/ 受保护的
时,实际上发生了什么?它们不是关键字,因此暗示它们必须是方法调用,但我找不到它们在哪里定义。他们似乎没有记录在案。声明私有
/ 受保护的
方法(如下所示)的两种不同方式是否实现不同? (第二种方法显然是方法调用,但是在第一种方法中并没有那么明显。)
What is actually occurring when private
/protected
is stated within a Ruby class definition? They are not keywords, so that implies they must be method calls, but I cannot find where they are defined. They do not appear to be documented. Are the two different ways of declaring private
/protected
methods (shown below) implemented differently? (The second way is obviously a method call, but this is not so apparent in the first way.)
class Foo
private
def i_am_private; end
def so_am_i; end
end
class Foo
def i_am_private; end
def so_am_i; end
private :i_am_private, :so_am_i
end
推荐答案
都是方法调用。引用 docs :
每个函数可以两种不同的方式使用。
Each function can be used in two different ways.
- 如果不带参数使用,这三个函数设置随后定义的方法的默认访问控制。
- 带有参数,这些函数设置命名方法和常量的访问控制。
在此处查看文档:
- Module.private
- Access Control
您正在寻找 Module.private
方法是如何形成的。 这就是发生的地方。并且此处是一些更多信息。您必须阅读更多内容,从 class.c
中定义的 rb_define_private_method
开始。
You were looking for how the Module.private
method comes into existence. Here is where that happens. And here is some more information about it. You would have to read more into it, starting from rb_define_private_method
defined in class.c
.
希望有帮助!
这篇关于当说明“私有” /“受保护”时,实际上发生了什么?在Ruby中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!