Module#protected
static VALUE
rb_mod_protected(int argc, VALUE *argv, VALUE module)
{
return set_visibility(argc, argv, module, METHOD_VISI_PROTECTED);
}
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
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
-
3.0
-
Module#public,Module#protected,Module#private,Module#public_class_method,Module#private_class_method, toplevel “private” and “public” methods now accept single array argument with a list of method names. [Feature #17314]
-