Explain the difference between public, private, and protected visibility in Ruby.
Last updated
Visibility controls who may call a method. public methods can be called by anyone, private methods only from within the same instance (no explicit receiver, with a small exception), and protected methods can be called with an explicit receiver but only from objects of the same class or subclass.
public: The default; part of the object's external API, callable from anywhere.private: Callable only without an explicit receiver, i.e. implicitly onself. Modern Ruby allowsself.setter=calls as an exception.protected: Callable with an explicit receiver as long as the caller is the same class or a relative; ideal for comparing two instances' internals.Key nuance: Ruby visibility is about the receiver syntax, not the calling location, which differs from many other languages.
[lang:ruby]
class Account
def >(other) = balance > other.balance # ok: protected on same class
protected
def balance = @balance
end
- https://www.turing.com/interview-questions/ruby
- https://www.youtube.com/watch?v=lkunzd5uDrw
- https://blog.jacobvosmaer.nl/0004-ruby-scheduler-interaction/
- https://wohotech.in/coding/top-java-interview-questions
- https://jetthoughts.com/blog/ruby-3-4-yjit-performance-guide/
- https://speed.ruby-lang.org/
- https://flexiple.com/python/interview-questions