Ruby Visibility
A well-designed class shows the world only what it needs. Ruby controls who may call a method with three visibility levels: public, private and protected. Hiding helper methods keeps a class's interface small, so you can change its internals later without breaking other code.
The three levels
| Level | Who can call it |
|---|---|
public (default) |
anyone |
private |
only the object itself, without an explicit receiver (or with self.) |
protected |
the object itself and other instances of the same class (or subclasses) |
private
Everything after the private keyword is private until the end of the class (or until another visibility keyword):
class PasswordChecker
def initialize(password)
@password = password
end
def strong?
long_enough? && mixed_case? && has_digit?
end
def report
checks = {length: long_enough?, case: mixed_case?, digit: has_digit?}
checks.map { |k, v| "#{k}:#{v ? 'ok' : 'missing'}" }.join(" ")
end
private
def long_enough? = @password.length >= 10
def mixed_case? = @password.match?(/[a-z]/) && @password.match?(/[A-Z]/)
def has_digit? = @password.match?(/\d/)
end
checker = PasswordChecker.new("Sunflower7")
p checker.strong?
puts PasswordChecker.new("hello").report
begin
checker.has_digit?
rescue NoMethodError => e
puts e.message
endtrue
length:missing case:missing digit:missing
private method 'has_digit?' called for an instance of PasswordChecker
The public methods strong? and report form the class's interface. The three helpers are implementation details.
private with a method name
private can also take method names — and since def returns the method's name as a symbol, you can mark a single method inline:
class Invoice
def initialize(amount) = @amount = amount
def total = @amount + tax
private def tax = (@amount * 0.2).round(2)
end
inv = Invoice.new(50)
p inv.total
p Invoice.private_method_defined?(:tax)
p Invoice.public_method_defined?(:total)60.0
true
true
Calling private methods with self.
Private methods can't be called on another object, but since Ruby 2.7 you may call them on self explicitly. This is necessary for private setters:
class Timer
def start
self.state = :running # private setter, needs self.
describe
end
private
attr_accessor :state
def describe = "Timer is #{state}"
end
p Timer.new.start"Timer is running"
protected
A protected method can be called on other instances of the same class. The classic use is comparing two objects by data you don't want to make public:
class Account
def initialize(owner, balance)
@owner = owner
@balance = balance
end
def richer_than?(other)
balance > other.balance # allowed: other is also an Account
end
protected
attr_reader :balance
end
a = Account.new("Kim", 800)
b = Account.new("Lou", 350)
p a.richer_than?(b)
begin
a.balance
rescue NoMethodError => e
puts e.message
endtrue
protected method 'balance' called for an instance of Account
If balance were private, other.balance would fail, because private methods cannot have an explicit receiver like other.
Private class methods
private inside the class body only affects instance methods. For class methods use private_class_method (or private inside class << self):
class Connection
def self.open(url)
validate!(url)
new(url)
end
def self.validate!(url)
raise ArgumentError, "bad url: #{url}" unless url.start_with?("https://")
end
private_class_method :validate!, :new
def initialize(url) = @url = url
def to_s = "Connection to #{@url}"
end
puts Connection.open("https://example.com")
[-> { Connection.new("x") }, -> { Connection.open("ftp://old") }].each do |attempt|
attempt.call
rescue NoMethodError, ArgumentError => e
puts "#{e.class}: #{e.message}"
endConnection to https://example.com
NoMethodError: private method 'new' called for class Connection
ArgumentError: bad url: ftp://old
Making new private forces everyone to use the factory method open.
Visibility is a guide, not a lock
Ruby trusts programmers. send can call private methods anyway, which is occasionally handy in tests or debugging. public_send respects visibility:
class Vault
private def secret = "42"
end
v = Vault.new
p v.send(:secret)
begin
v.public_send(:secret)
rescue NoMethodError
puts "public_send refuses"
end"42"
public_send refuses
Tip: Make methods private by default and promote them to public only when other code needs them. A small public interface is easier to document, test and keep stable.
Test yourself
Which call is allowed for a private method helper?
other_obj.helperhelperinside the same objectMyClass.helperobj.helperfrom outside
When is protected useful?
- To hide a method from subclasses
- To let instances of the same class call the method on each other
- To make a method run faster
- To make class methods private
Which method calls a method while respecting its visibility?
send__send__public_sendcall