Skip to content
instance method

Module#protected

() -> nil
(::Symbol method_name) -> ::Symbol
(::Symbol, ::Symbol, *::Symbol method_name) -> ::Array[::Symbol]
(::string method_name) -> ::string
(::interned, ::interned, *::interned method_name) -> ::Array[::interned]
(::Array[::interned]) -> ::Array[::interned]
protected → nil
protected(method_name) → method_name
protected(method_name, method_name, ...) → array
protected(array) → array

Sets the visibility of a section or of a list of method names as protected. Accepts no arguments, a splat of method names (symbols or strings) or an array of method names. Returns the arguments that it received.

Important difference between protected in other languages

Protected methods in Ruby are different from other languages such as Java, where methods are marked as protected to give access to subclasses. In Ruby, subclasses already have access to all methods defined in the parent class, even private ones.

Marking a method as protected allows different objects of the same class to call it.

One use case is for comparison methods, such as ==, if we want to expose a method for comparison between objects of the same class without making the method public to objects of other classes.

Performance considerations

Protected methods are slower than others because they can’t use inline cache.

Example

Example
class Account
  # Mark balance as protected, so that we can compare between accounts
  # without making it public.
  attr_reader :balance
  protected :balance

  def initialize(balance)
    @balance = balance
  end

  def >(other)
    # The invocation to `other.balance` is allowed because `other` is a
    # different object of the same class (Account).
    balance > other.balance
  end
end

account1 = Account.new(100)
account2 = Account.new(50)

account1 > account2  # => true (works)
account1.balance     # => NoMethodError (fails because balance is not public)

To show a private method on RDoc, use :doc: instead of this.

Ruby version changes

  1. 3.0