What Are Public, Protected and Private Methods in Ruby?

public method is a method that is available to anyone who knows either the class name or the object’s name. In other words, a public method can be accessed from both inside and outside the class.

Meanwhile, private and protected methods are not accessible from outside the class. The only way to access them is through a public method.

The difference between these access controls will be on Visibility and how they are affected by Inheritance  :

Let’s talk about Visibility

Who gets to talk to everyone in public? It is the one and only, Public method.

Who can’t communicate with the world directly? Sadly, it is Private and Protected methods (wait, no, it is not sad, we need them to be like that).

Public method is pretty straight forward. I have noticed a lot of people grasped the concept easily, but some struggle (honestly, myself included) with the other two methods, Private and Protected.

So, now let’s focus on Private and Protected and how are they similar and different to each other.

The similarity between Protected and Private :

– Both can be accessed from outside the class through a public method.

The differences between Protected and Private are :

– Private method can not be called with a receiver (not even with #self). Unless … calling a Private setter method. If you try to remove the receiver, Ruby will create a local variable. Self is necessary in this case.

– Protected may or may not use a receiver such as #self.

– Protected can access another object’s protected method that comes from the same class, Private can not.

class Dog
  attr_accessor :name, :age

  def initialize(n, a)
    self.name = n
    self.age = a
  end

  def accessing_private
    "#{self.name} in human years is #{human_years}. This is secret!"
  end

  def accessing_protected
    "Will this work? " + a_protected_method
  end

  def eat_more_than(other) 
  # accessing other instance's protected method from the same class
    daily_diet < other.daily_diet 
    "#{name} eats more than #{other.name}"
  end
  
  def boy 
    gender_method("boy") # accessing private setter method
  end
  
  protected

  def daily_diet 
    age * 2 # the younger, the more they have to eat 
  end

  def a_protected_method
    "Yes, I'm protected!"
  end

  private
  
  attr_writer :gender
  
  def gender_method(gender)
    self.gender = gender # private setter method requires self
    "#{name} is a #{gender}"
  end
  
  def human_years
    age * 8
  end
end

# Create the first object of Dog
blake = Dog.new("Blake", 5)

p blake.accessing_private # "Blake in human years is 16. This is secret!"

p blake.accessing_protected # "Will this work? Yes, I'm protected!"

# Create the second object of Dog
jackson = Dog.new("Jackson", 1)

# Below, protected methods from different objects of the same type/class 
# are proven to share access
p jackson.eat_more_than(blake) # true -> "Jackson eats more than Blake"

# Below, accessing private setter method through a public method.
p blake.boy # Blake is a boy 

Time for Inheritance!

In Ruby, the inheritance hierarchy does not really enter into the equation. It is rather all about ‘the receiver‘.

– Private methods can only be called on subclasses implicitly (only call the name of the method) but not explicitly (using #self).

– Protected can be called both ways (with or without #self || implicitly or explicitly).

Example with code below :

class Puppy < Dog 
  
  def accessing_protected_explicitly
    "Explicitly calls '#{self.a_protected_method}'"
  end
  
  def accessing_protected_implicitly
    "Call protected method implicitly '#{a_protected_method}'"
  end 
  
  def accessing_private_implicitly 
    "#{self.name} is #{human_years} years old in human years. This is a secret!" 
  end 
  
  def accessing_private_explicitly
    "#{self.name} is #{self.human_years} years old in human years" # error
  end 
end 

# Below, testing them on a subclass 
booboo = Puppy.new("Booboo", 1 )
p booboo.accessing_protected_explicitly # works 
p booboo.accessing_protected_implicitly # works
p booboo.accessing_private_implicitly # works 
p booboo.accessing_private_explicitly # error, called on a receiver

The bottom line is that we can always call a private method implicitly from within a class it is declared in, as well as all subclasses of this class. While a protected method can be called either way.

 

19 Comments

  1. Cydrodo December 8, 2020 at 7:29 pm

    Comprar Viagra Por Internet En Espana accuttincant cialis online purchase Mentitunty On Line Hydrochlorothiazide

  2. 720p izle December 10, 2020 at 2:01 am

    You are my inspiration , I have few web logs and very sporadically run out from to brand. Frieda Raleigh Jaylene

  3. edmond barash December 31, 2020 at 6:19 pm

    I like and follow your site, thanks

  4. bennett costella January 1, 2021 at 3:42 am

    You produce quality content, congratulations on this

  5. concetta annon January 1, 2021 at 6:22 pm

    Thanks so much for the blog post.Thanks Again. Great.

  6. edmond barash January 3, 2021 at 2:14 am

    I really like the design and contents of your web page

  7. jaime grimaldi January 4, 2021 at 11:35 am

    Very informative blog article.Much thanks again. Fantastic.

  8. jude allegrini January 6, 2021 at 11:44 am

    You have a quality site, I congratulate you on this

  9. emil kitcher January 9, 2021 at 2:10 pm

    I loved your blog.Really looking forward to read more. Will read on…

  10. music January 9, 2021 at 6:02 pm

    Greate article. Keep writing such kind of info on your blog.

  11. instagram döl israfı January 14, 2021 at 8:34 pm

    Exceptional post however , I was wondering if you could write a litte more on this topic?
    I’d be very grateful if you could elaborate a little bit
    more. Bless you!

  12. türk uygulamalı porno January 15, 2021 at 3:33 am

    I got this website from my friend who told me on the topic of this web site and
    at the moment this time I am browsing this web page and reading very
    informative articles or reviews here.

  13. instagram döl israfı January 15, 2021 at 6:41 am

    You have made some decent points there. I checked on the net to
    learn more about the issue and found most individuals will go along with your views on this
    site.

  14. instagram ucuz porno satın al January 15, 2021 at 12:59 pm

    Every weekend i used to pay a quick visit this website, for the reason that i want enjoyment, since
    this this site conations genuinely good funny stuff too.

  15. porno izledim January 15, 2021 at 8:32 pm

    Unquestionably believe that which you stated. Your favourite reason appeared to be at the internet the simplest thing to keep in mind of.
    I say to you, I definitely get irked at the same time
    as people consider issues that they plainly do not know about.
    You managed to hit the nail upon the top and defined out
    the whole thing without having side-effects , other people could take a signal.

    Will probably be again to get more. Thank you

  16. Yüz bakım ürünleri January 17, 2021 at 1:32 pm

    I really love your blog.. Excellent colors & theme. Did you make this amazing site yourself?
    Please reply back as I’m hoping to create my own personal
    website and would like to know where you got this from or what the theme is named.
    Thanks!

  17. emil kitcher January 18, 2021 at 1:13 am

    Wow, great blog article.Really thank you! Really Great.

  18. hard January 21, 2021 at 10:26 am

    If you are going for best contents like I do, only go to see this web page all the time because it presents feature contents, thanks

  19. wso shell txt January 21, 2021 at 1:32 pm

    Hi there, after reading this amazing article i am too cheerful to share my knowledge here
    with mates.

Leave a comment

Your email address will not be published. Required fields are marked *