ruby - 使用私有(private) attr_accessor 时,为什么 self.attribute= 起作用,而 self.attribute 不起作用?

标签 ruby

假设我有一个类,我在其中定义了一个 attr_accessor,如下所示:

private

attr_accessor :attribute

我理解为什么使用 self.attribute 读取器方法不起作用 - 在 Ruby 中,您不能在显式接收器上调用私有(private)方法。

令我困惑的是,为什么这条规则不适用于作者?为什么我可以调用 self.attribute = 1,并且不会引发任何访问冲突错误?

最佳答案

根据@Jörg W Mittag 对 Alan Skorkin 博客条目的评论 Ruby Access Control – Are Private And Protected Methods Only A Guideline? :

Quick note: there is a special case where calling private methods with an explicit receiver is allowed:

If the method name ends with '=' (i.e. it is an attribute writer) and the explicit receiver is 'self', then this works. This is necessary, because setters can only be called with an explicit receiver because of the method/variable ambiguity. Otherwise it wouldn't be possible to call private setters.

Jörg 没有引用任何消息来源,但他非常可靠。

关于ruby - 使用私有(private) attr_accessor 时,为什么 self.attribute= 起作用,而 self.attribute 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45701663/

相关文章:

mysql - Ruby DataObjects::SQLError 查询不包含字符串参数

ruby-on-rails - 如何验证大 XML

ruby-on-rails - 使用 Rails 时,在 Ruby 中处理常量的最佳方法是什么?

ruby-on-rails - Ruby 2.0 是否改变了 SimpleDelegator 的行为?

ruby-on-rails - 将 JRuby 与 Rails 3.2 结合使用

ruby - 带有 X509 证书的 Ruby 中的 SOAP 请求

ruby-on-rails - Rails Ruby 哈希数组按键合并为平均值

ruby - Bundler 未正确安装

ruby - 如何告诉 Rubocop 只查看特定目录?

ruby-on-rails - 如何切换到旧版本的 ruby​​/rails 环境?