Zachary Wright Zachary Wright - 1 year ago 50
Ruby Question

When using a private attr_accessor, why does self.attribute= work, but self.attribute doesn't?

Suppose I have a class where I define an

like so:


attr_accessor :attribute

I understand why using the
reader method doesn't work - in Ruby you can't call a private method on an explicit receiver.

What I'm confused by is why doesn't this rule apply to the writer? Why can I call
self.attribute = 1
, and that doesn't throw any access violation errors?

Answer Source

According to a comment by @Jörg W Mittag to Alan Skorkin's blog entry 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 cites no sources, but he's pretty reliable.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download