# When to Use Protected vs. Private?

**URL:** <https://www.ruby-forum.com/t/when-to-use-protected-vs-private/52886>\
**Category:** Ruby\
**Created:** [January 19, 2006, 10:59pm UTC](https://www.ruby-forum.com/t/when-to-use-protected-vs-private/52886 "2006-01-19T22:59:45Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![tcsnide](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/eb8c5e/32.png) [@tcsnide](https://www.ruby-forum.com/u/tcsnide)\
**Post date:** [January 19, 2006, 10:59pm UTC](https://www.ruby-forum.com/t/when-to-use-protected-vs-private/52886/1 "2006-01-19T22:59:45Z")

</div>

Can someone clarify the difference between declaring a method Protected  
vs. Private?

I thought that a private method could only be accessed within the  
specific defining class. However, it may also be called by subclasses.  
So why the need for protected?

Thanks in advance!

---

<div class="post-metadata">

**Author:** ![tcsnide](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/eb8c5e/32.png) [@tcsnide](https://www.ruby-forum.com/u/tcsnide)\
**Post date:** [January 19, 2006, 11:47pm UTC](https://www.ruby-forum.com/t/when-to-use-protected-vs-private/52886/2 "2006-01-19T23:47:56Z")

</div>

Hi –

On Fri, 20 Jan 2006, Thomas S. wrote:

> Can someone clarify the difference between declaring a method Protected  
> vs. Private?
> 
> I thought that a private method could only be accessed within the  
> specific defining class. However, it may also be called by subclasses.  
> So why the need for protected?

A private method can only be called with no explicit receiver. That  
means that the receiver has to be “self” – because that’s the only  
time there can be no explicit receiver. (Private methods ending in  
“=” do allow an explicit receiver, because they have to so that they  
won’t be parsed as variable assignments.)

What protected does is to let you call a method _with_ an explicit  
receiver, as long as that receiver is of the same class is “self”.

That means you can do things like:

def compare\_with(other)  
self.x \<=\> other.x  
end

even if x is protected, whereas you can’t do that from the outside  
(without instance\_eval or some other “invasive” technique).

David

–  
David A. Black  
removed\_email\_address@domain.invalid

“Ruby for Rails”, from Manning Publications, coming April 2006!

> **[Ruby for Rails](https://www.manning.com/books/ruby-for-rails)**
>
> NEWER EDITION AVAILABLE
> 
> The Well-Grounded Rubyist, Second Edition is now available. An eBook of the previous edition, The Well-Grounded Rubyist is included at no additional cost when you buy the revised edition! 
> 
> 
> Ruby for Rails helps Rails...
