Why does Ruby have both private and protected methods?
Asked Answered
H

8

150

Before I read this article, I thought access control in Ruby worked like this:

  • public - can be accessed by any object (e.g. Obj.new.public_method)
  • protected - can only be accessed from within the object itself, as well as any subclasses
  • private - same as protected, but the method doesn't exist in subclasses

However, it appears that protected and private act the same, except for the fact that you can't call private methods with an explicit receiver (i.e. self.protected_method works, but self.private_method doesn't).

What's the point of this? When is there a scenario when you wouldn't want your method called with an explicit receiver?

Houseyhousey answered 20/8, 2010 at 20:1 Comment(1)
If all instances of Object were allowed to call the private methods of every other instance of Object, it'd be possible to say things like 5.puts("hello world").Ronnie
C
175

protected methods can be called by any instance of the defining class or its subclasses.

private methods can be called only from within the calling object. You cannot access another instance's private methods directly.

Here is a quick practical example:

def compare_to(x)
 self.some_method <=> x.some_method
end

some_method cannot be private here. It must be protected because you need it to support explicit receivers. Your typical internal helper methods can usually be private since they never need to be called like this.

It is important to note that this is different from the way Java or C++ works. private in Ruby is similar to protected in Java/C++ in that subclasses have access to the method. In Ruby, there is no way to restrict access to a method from its subclasses like you can with private in Java.

Visibility in Ruby is largely a "recommendation" anyways since you can always gain access to a method using send:

irb(main):001:0> class A
irb(main):002:1>   private
irb(main):003:1>   def not_so_private_method
irb(main):004:2>     puts "Hello World"
irb(main):005:2>   end
irb(main):006:1> end
=> nil

irb(main):007:0> foo = A.new
=> #<A:0x31688f>

irb(main):009:0> foo.send :not_so_private_method
Hello World
=> nil
Cheiro answered 20/8, 2010 at 20:20 Comment(3)
Ah, ok that makes a lot more sense. My misunderstanding came from thinking private vs protected had to do whether a subclass could inherit a method, but it's actually about where the method can be called from. Thanks!Houseyhousey
Also private methods are ignored by default by RDoc when generating documentation while protected ones are not. You can always use the --all flag to include them.Cioffred
But if you really want it private, can't you override send?Deus
U
83

The difference

  • Anyone can call your public methods.
  • You can call your protected methods, or another member of your class (or a descendant class) can call your protected methods from the outside. Nobody else can.
  • Only you can call your private methods, because they can only be called with an implicit receiver of self. Even you cannot call self.some_private_method; you must call private_method with self implied.
    • iGEL points out: "There is one exception, however. If you have a private method age=, you can (and have to) call it with self to separate it from local variables."
    • Since Ruby 2.7 the self receiver can be explicit, self.some_private_method is allowed. (Any other explicit receiver is still disallowed, even if the runtime value is the same as self.)

In Ruby, these distinctions are just advice from one programmer to another. Non-public methods are a way of saying "I reserve the right to change this; don't depend on it." But you still get the sharp scissors of send and can call any method you like.

A brief tutorial

# dwarf.rb
class Dwarf
  include Comparable

  def initialize(name, age, beard_strength)
    @name           = name
    @age            = age
    @beard_strength = beard_strength
  end

  attr_reader :name, :age, :beard_strength
  public    :name
  private   :age
  protected :beard_strength

  # Comparable module will use this comparison method for >, <, ==, etc.
  def <=>(other_dwarf)
    # One dwarf is allowed to call this method on another
    beard_strength <=> other_dwarf.beard_strength
  end

  def greet
    "Lo, I am #{name}, and have mined these #{age} years.\
       My beard is #{beard_strength} strong!"
  end

  def blurt
    # Not allowed to do this: private methods can't have an explicit receiver
    "My age is #{self.age}!"
  end
end

require 'irb'; IRB.start

Then you can run ruby dwarf.rb and do this:

gloin = Dwarf.new('Gloin', 253, 7)
gimli = Dwarf.new('Gimli', 62,  9)

gloin > gimli         # false
gimli > gloin         # true

gimli.name            # 'Gimli'
gimli.age             # NoMethodError: private method `age'
                         called for #<Dwarf:0x007ff552140128>

gimli.beard_strength # NoMethodError: protected method `beard_strength'
                        called for #<Dwarf:0x007ff552140128>

gimli.greet          # "Lo, I am Gimli, and have mined these 62 years.\
                           My beard is 9 strong!"

gimli.blurt          # private method `age' called for #<Dwarf:0x007ff552140128>
Ultrared answered 18/3, 2013 at 14:39 Comment(3)
Nice explanation! There is one exception however. If you have a private method age=, you can (and have to) call it with self to separate it from local variables.Gifted
If you made "greet" a protected method, why can't you do a gimli.greet ? Since gimli is a member of the Dwarf class, shouldn't it be able to call this method without harassment?Becka
@Becka because when you do gimli.greet, gimli isn't the caller, but the receiver. The caller is the "top-level execution environment", which is actually an ad-hoc instance of Object. Try this: ruby -e 'p self; p self.class'Hamstring
E
58

Private methods in Ruby:

If a method is private in Ruby, then it cannot be called by an explicit receiver (object). It can only be call implicitly. It can be called implicitly by the class in which it has been described in as well as by the subclasses of this class.

The following examples will illustrate it better:

1) A Animal class with private method class_name

class Animal
  def intro_animal
    class_name
  end
  private
  def class_name
    "I am a #{self.class}"
  end
end

In this case:

n = Animal.new
n.intro_animal #=>I am a Animal
n.class_name #=>error: private method `class_name' called

2) A subclass of Animal called Amphibian:

class Amphibian < Animal
  def intro_amphibian
    class_name
  end 
end 

In this case:

  n= Amphibian.new
  n.intro_amphibian #=>I am a Amphibian
  n.class_name #=>error: private method `class_name' called

As you can see, private methods can be called only implicitly. They cannot be called by explicit receivers. For the same reason, private methods cannot be called outside the hierarchy of the defining class.

Protected Methods in Ruby:

If a method is protected in Ruby, then it can be called implicitly by both the defining class and its subclasses. Additionally they can also be called by an explicit receiver as long as the receiver is self or of same class as that of self:

1) A Animal class with protected method protect_me

class Animal
  def animal_call
    protect_me
  end
  protected
  def protect_me
    p "protect_me called from #{self.class}"
  end  
end

In this case:

n= Animal.new
n.animal_call #=> protect_me called from Animal
n.protect_me #=>error: protected method `protect_me' called

2) A mammal class which is inherited from animal class

class Mammal < Animal
  def mammal_call
    protect_me
  end
end 

In this case

n= Mammal.new
n.mammal_call #=> protect_me called from Mammal

3) A amphibian class inherited from Animal class (same as mammal class)

class Amphibian < Animal
  def amphi_call
    Mammal.new.protect_me #Receiver same as self
    self.protect_me  #Receiver is self
  end   
end

In this case

n= Amphibian.new
n.amphi_call #=> protect_me called from Mammal
             #=> protect_me called from Amphibian  

4) A class called Tree

class Tree
  def tree_call
    Mammal.new.protect_me #Receiver is not same as self
  end
end

In this case:

n= Tree.new
n.tree_call #=>error: protected method `protect_me' called for #<Mammal:0x13410c0>
Epiphysis answered 17/1, 2015 at 21:50 Comment(0)
F
7

Consider a private method in Java. It can be called from within the same class, of course, but it can also be called by another instance of that same class:

public class Foo {

   private void myPrivateMethod() {
     //stuff
   }

   private void anotherMethod() {
       myPrivateMethod(); //calls on self, no explicit receiver
       Foo foo = new Foo();
       foo.myPrivateMethod(); //this works
   }
}

So -- if the caller is a different instance of my same class -- my private method is actually accessible from the "outside", so to speak. This actually makes it seem not all that private.

In Ruby, on the other hand, a private method really is meant to be private only to the current instance. This is what removing the option of an explicit receiver provides.

On the other hand, I should certainly point out that it's pretty common in the Ruby community to not use these visibility controls at all, given that Ruby gives you ways to get around them anyway. Unlike in the Java world, the tendency is to make everything accessible and trust other developers not to screw things up.

Filibertofilibuster answered 20/8, 2010 at 20:27 Comment(3)
"it's pretty common in the Ruby community to not use these visibility controls at all" - this may be true, but I'd say we should use them. Like constants, they are not handcuffs, but a communication from one programmer to another: "I advise you to leave this alone." You can depend on my public methods; I may change my private methods without warning, because I consider them implementation details.Ultrared
In Ruby, on the other hand, a private method really is meant to be private only to the current instance.” This is not true. You can still accidentally overwrite private methods from your parent class (and some class even list this as part of their API).Newman
@FranklinYu That has no bearing on what he wrote; privacy in Ruby is about objects, not classes, and it's about calling methods, not defining them. A private method can only be called by another method of the same object; it doesn't have anything to do with what class the method was defined in.Zerlina
P
5

What's the difference?

Private Methods Explained

@freddie = Person.new
@freddie.hows_it_going?
# => "oh dear, i'm in great pain!"

class Person   
    # public method
    def hows_it_going?
        how_are_your_underpants_feeling?
    end

    private

    def how_are_your_underpants_feeling? # private method
        puts "oh dear, i'm in great pain!"
    end
end

We can ask Freddie how things are going given it's a public method. That's perfectly valid. And it's normal and accepted.

But...the only person who can know how Freddie's underpants situation is, is Freddie himself. It would not do for random strangers to reach into Freddy's underpants - no, no -- it's very, very private, and we don't want to expose what's private to the outside world. In other words, we may not want to expose mutable data, to any caller in the world. Someone could mutate a value, and we'd be in a world of pain trying to discover where the bug came from.

@freddie.how_are_your_underpants_feeling?
# => # NoMethodError: private method `how_are_your_underpants_feeling?' called

Protected Methods Explained

Consider this:

class Person    
    protected

    def hand_over_the_credit_card! # protected method
        puts "Lawd have mercy. Whatever. Here it is: 1234-4567-8910"
    end
end

class Rib < Person
end

class Wife < Rib # wife inherits from Rib
    def i_am_buying_another_handbag_with_your_card(husband)        
        husband.hand_over_the_credit_card! # equalityInAction    
    end
end

@husband = Person.new
@mrs = Wife.new
@mrs.i_am_buying_another_handbag_with_your_card(@husband)
# => puts "Lawd have mercy. Whatever. Here it is: 1234-4567-8910"

We're somewhat ok with mrs getting our credit card details, given mrs is flesh of our flesh, inherited from Person, so she can blow it on some shoes etc., but we don't want random individuals getting access to our credit card details.

If we tried to do that outside the subclass, it would fail:

@mrs = Wife.new
@mrs.hand_over_the_credit_card!
# => protected method hand_over_the_credit_card! called for #<Wife:0x00005567b5865818> (NoMethodError)

Summary

  • private methods can only be called from within, and without "an explicit receiver". (Strictly speaking, you can access a private method using a little bit of ruby magic, but I'm going to ignore that for the moment).
  • protected methods can be called within sub-classes.
  • I used the examples/analogies to help you vividly remember.
Pengelly answered 2/2, 2021 at 23:10 Comment(0)
I
4

Part of the reason why private methods can be accessed by subclasses in Ruby is that Ruby inheritance with classes is thin sugarcoating over Module includes - in Ruby, a class, in fact, is a kind of module that provides inheritance, etc.

http://ruby-doc.org/core-2.0.0/Class.html

What this means is that basically a subclass "includes" the parent class so that effectively the parent class's functions, including private functions, are defined in the subclass as well.

In other programming languages, calling a method involves bubbling the method name up a parent class hierarchy and finding the first parent class that responds to the method. By contrast, in Ruby, while the parent class hierarchy is still there, the parent class's methods are directly included into the list of methods of the subclass has defined.

Impalpable answered 21/2, 2015 at 1:27 Comment(0)
D
3

Comparison of access controls of Java against Ruby: If method is declared private in Java, it can only be accessed by other methods within the same class. If a method is declared protected it can be accessed by other classes which exist within the same package as well as by subclasses of the class in a different package. When a method is public it is visible to everyone. In Java, access control visibility concept depends on where these classes lie's in the inheritance/package hierarchy.

Whereas in Ruby, the inheritance hierarchy or the package/module don't fit. It's all about which object is the receiver of a method.

For a private method in Ruby, it can never be called with an explicit receiver. We can (only) call the private method with an implicit receiver.

This also means we can call a private method from within a class it is declared in as well as all subclasses of this class.

class Test1
  def main_method
    method_private
  end

  private
  def method_private
    puts "Inside methodPrivate for #{self.class}"
  end
end

class Test2 < Test1
  def main_method
    method_private
  end
end

Test1.new.main_method
Test2.new.main_method

Inside methodPrivate for Test1
Inside methodPrivate for Test2

class Test3 < Test1
  def main_method
    self.method_private #We were trying to call a private method with an explicit receiver and if called in the same class with self would fail.
  end
end

Test1.new.main_method
This will throw NoMethodError

You can never call the private method from outside the class hierarchy where it was defined.

Protected method can be called with an implicit receiver, as like private. In addition protected method can also be called by an explicit receiver (only) if the receiver is "self" or "an object of the same class".

 class Test1
  def main_method
    method_protected
  end

  protected
  def method_protected
    puts "InSide method_protected for #{self.class}"
  end
end

class Test2 < Test1
  def main_method
    method_protected # called by implicit receiver
  end
end

class Test3 < Test1
  def main_method
    self.method_protected # called by explicit receiver "an object of the same class"
  end
end


InSide method_protected for Test1
InSide method_protected for Test2
InSide method_protected for Test3


class Test4 < Test1
  def main_method
    Test2.new.method_protected # "Test2.new is the same type of object as self"
  end
end

Test4.new.main_method

class Test5
  def main_method
    Test2.new.method_protected
  end
end

Test5.new.main_method
This would fail as object Test5 is not subclass of Test1
Consider Public methods with maximum visibility

Summary

Public: Public methods have maximum visibility

Protected: Protected method can be called with an implicit receiver, as like private. In addition protected method can also be called by an explicit receiver (only) if the receiver is "self" or "an object of the same class".

Private: For a private method in Ruby, it can never be called with an explicit receiver. We can (only) call the private method with an implicit receiver. This also means we can call a private method from within a class it is declared in as well as all subclasses of this class.

Dumas answered 18/7, 2017 at 3:50 Comment(0)
D
0

First Three types of access specifiers and those define thier scope.

  1. Public -> Access anywhere out side the class.
  2. Private -> Can not access outside the class.
  3. Protected -> This Method not access anywhere this method define scope.

But I have a solution for this problem for all method how to access explain in depth.

class Test
  attr_reader :name

  def initialize(name)
    @name = name
  end
  
  def add_two(number)
    @number = number 
  end
  
  def view_address
    address("Anyaddress")
  end
  
  private 

  def address(add)
    @add = add
  end
  
  protected 

  def user_name(name)
    # p 'call method'
    @name = name
  end
end

class Result < Test
  def new_user
    user_name("test355")
  end
end
  1. Object List
  2. p test = Test.new("test")
  3. p test.name
  4. p test.add_two(3)
  5. List item
  6. p test.view_address
  7. p r = Result.new("")
  8. p r.new_user
Downright answered 19/9, 2019 at 7:2 Comment(1)
Some issue in edit the code. Second class show in a single line previous post. Now i explain how to access all method.First Create Test class object.but private method can not access outside class then access private method. we create view_address method access through the main object. and also protected method access the create the inheritance.Downright

© 2022 - 2024 — McMap. All rights reserved.