Before I read this article, I thought access control in Ruby worked like this:
public– can be accessed by any object (e.g.Obj.new.public_method)protected– can only be accessed from within the object itself, as well as any subclassesprivate– same as protected, but the method doesn’t exist in subclasses
However, it appears that protected and private act the same, except for the fact that you can’t call private methods with an explicit receiver (i.e. self.protected_method works, but self.private_method doesn’t).
What’s the point of this? When is there a scenario when you wouldn’t want your method called with an explicit receiver?
protectedmethods can be called by any instance of the defining class or its subclasses.privatemethods can be called only from within the calling object. You cannot access another instance’s private methods directly.Here is a quick practical example:
some_methodcannot beprivatehere. It must beprotectedbecause you need it to support explicit receivers. Your typical internal helper methods can usually beprivatesince they never need to be called like this.It is important to note that this is different from the way Java or C++ works.
privatein Ruby is similar toprotectedin Java/C++ in that subclasses have access to the method. In Ruby, there is no way to restrict access to a method from its subclasses like you can withprivatein Java.Visibility in Ruby is largely a “recommendation” anyways since you can always gain access to a method using
send: