Skip to content
Tutorials Center
My learning

Topics

Lesson 53 of 134 ยท Object-Oriented Ruby

public, private and protected

Understand Ruby method visibility - public, private and protected, how self receivers work, private_class_method, private_constant, send versus public_send, and common mistakes.

Every method in a Ruby class has a visibility that controls who may call it. Visibility is how you tell the rest of the program, "this is the interface, and that is my own business". A class with a small public surface is easy to use and easy to change, because nothing outside can depend on the parts you keep private.

Ruby has three levels: public, private and protected. Their names are familiar from other languages, but the rules differ in an important way. Ruby does not look at who owns the code that makes the call. It looks at the receiver: the object written before the dot. Once you understand that, the sometimes surprising behavior of private becomes simple. This lesson covers the three levels, the different ways to declare them, class-level and constant visibility, and the escape hatches that exist (and why you should rarely use them).

Public: the default

Methods are public unless you say otherwise. Anyone can call them from anywhere.

Ruby Public methods are the default

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The last line lists [:increment, :value]. The method initialize is missing because Ruby always makes it private automatically; you never want obj.initialize to reset an existing object. Passing false asks only for methods defined in this class, not inherited ones.

Private: only without an explicit receiver

A private method can be called only with an implicit receiver, meaning without writing something. in front of it. The caller is always the current object.

Ruby Calling a private method from outside (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

can_afford? calls usable_funds, which calls fee, all on the implicit self, so everything works and the program prints true and false. respond_to?(:fee) is false, because by default respond_to? ignores private methods. The final line fails with main.rb:19:in '<main>': private method 'fee' called for an instance of Account (NoMethodError). Ruby's message says exactly what happened: you named the receiver a, so the call was not allowed.

The word private on its own line affects every method defined after it, up to the end of the class body or the next visibility keyword. It is a method call, not a block, and its indentation is only a convention. Indenting methods under private shows the reader what is covered.

Private in Ruby does not mean "only this class". Subclasses inherit private methods and can call them without a receiver. Private means "only the object itself". If you want to stop even subclasses, Ruby has no direct way; use composition or a different design.

Three ways to declare visibility

Besides the bare keyword, private accepts the names of methods. Since def returns the method name as a symbol, you can wrap the definition directly.

Ruby Three declaration styles

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The first list is [:footer, :header, :secret_code] and the second [:body, :render, :title, :visible]. Style 2 (private def ...) is popular in modern Ruby because the keyword sits right next to the method it protects. Style 1 is handy when you want to list the private methods in one place. Whichever you choose, keep one style per class so readers do not have to guess.

The self rule and writers

There is one famous exception to "no explicit receiver". Because x = 5 inside a method creates a local variable, you cannot call a writer method with plain assignment; you must write self.x = 5. Ruby therefore allows self. as a receiver for private setters.

Ruby Private setters and self

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The class keeps its counter behind a private accessor. Inside the class self.elapsed += 1 works; the prints show 2, then private method 'elapsed=' called for an instance of Timer, then private method 'elapsed' called for an instance of Timer. Since Ruby 2.7, calling any private method with a literal self. receiver is allowed (self.helper), but a plain helper is still the usual style. A private attr_accessor is a neat way to keep state and its accessors available to yourself only.

Protected: private to outsiders, open to relatives

A protected method can be called with an explicit receiver, but only when the caller is itself an instance of the same class (or a subclass). It exists for comparisons: "let objects of the same kind look at each other's insides, but nobody else".

Ruby protected for comparing two objects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Inside richer_than? the call other.balance has an explicit receiver, yet it is allowed, because the caller (self) is also a Wallet. From outside, a.balance fails with protected method 'balance' called for an instance of Wallet. Compare that with private, where other.balance would be rejected even inside the class.

Protected is much rarer in Ruby than in Java or C++. Often a public reader method is simpler, or the comparison belongs in <=> (Comparable). Use protected when the value is truly internal but two instances must read it.

Visibility is not security

Ruby will not stop a determined programmer. send ignores visibility, and public_send respects it.

Ruby send versus public_send

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

send(:combination) prints 12-34-56. public_send fails with private method 'combination' called for an instance of Vault. The optional second argument of respond_to? includes private methods when true. This is by design: tests and debuggers sometimes need to reach inside. Treat private as a strong signal to other programmers, not a lock. Calling send on someone else's private method means you rely on code that may change at any time, so do it only in tests, debugging tools and metaprogramming where you control both sides.

Class methods and constants

Plain private affects instance methods only. A def self.helper stays public, even after a private line. Use private_class_method instead.

Ruby private_class_method and private_constant

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Three lessons in one example. First, private_class_method :new turns the constructor private, so the only way to get an object is Config.instance (a hand-made singleton; the standard library has a ready one, see Observable, Singleton and Standard Patterns). The error is private method 'new' called for class Config. Second, private_constant hides SECRET: inside the class it works (token_length returns 6), from outside you get a NameError with the message private constant Config::SECRET referenced. Third, a def self.hidden placed after private is still public. Ruby prints no warning for it, so write private_class_method :hidden or put the methods inside class << self followed by private (Singleton Methods and the Singleton Class).

Changing visibility when inheriting

A subclass may redeclare visibility. Making a parent's public method private in the child is legal, but it breaks the idea that a child can be used wherever the parent can (see Inheritance).

Ruby Overriding visibility in a subclass

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

private :speak in Dog creates a private entry that calls the inherited method, and Animal itself is unchanged. The last line prints [:speak]. Code that handles a Dog as an Animal and calls speak will break, so this pattern is rare in practice. The reverse is more common: initialize and helper methods start private, and a subclass makes a particular one public.

Practical advice

  • Start private, widen later. Make helpers private by default and public only what callers need. It is easy to open a method later and painful to take a public method away.
  • Test public behavior. If you feel you must test a private method directly, it may deserve to be its own small class.
  • Avoid protected unless two instances really need to peek. Prefer public readers or <=>.
  • Prefer public_send when the method name comes from outside data (user input, config); send there could invoke private methods.
  • Do not hide everything. Ruby culture trusts programmers, and an over-defensive class with dozens of private methods is as hard to extend as an open one is to protect.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What decides whether a private method call is allowed?

    Ruby checks the receiver. A private method can only be called without an explicit receiver (or with a literal self).
  2. 2. Can a subclass call a private method it inherited from its parent?

    Ruby's private is about the receiver, not the class. Subclasses inherit private methods and can call them on self.
  3. 3. What is protected mainly used for?

    A protected method may be called with an explicit receiver by another instance of the class or a subclass, which suits comparison code.
  4. 4. You write private followed by def self.build; end. What is the visibility of build?

    Use private_class_method or class << self with private to make class methods private.
  5. 5. What is the difference between send and public_send?

    send bypasses visibility, so use it only when you control both sides. public_send respects private and protected.

Summary

  • Methods are public by default; initialize is always private.
  • private allows calls only without an explicit receiver (or with self.), and subclasses inherit private methods.
  • protected allows explicit-receiver calls from instances of the same class, mainly for comparisons.
  • Declare visibility with a bare keyword, private :name, or private def name.
  • Class methods need private_class_method; constants need private_constant.
  • send bypasses visibility, public_send respects it. Visibility is a signal to other programmers, not a security boundary.
  • Keep the public interface small and widen it only when needed.

Next: Equality and Identity