# Private methods in Ruby

**URL:** <https://www.ruby-forum.com/t/private-methods-in-ruby/79071>\
**Category:** Ruby\
**Created:** [December 12, 2006, 12:30am UTC](https://www.ruby-forum.com/t/private-methods-in-ruby/79071 "2006-12-12T00:30:35Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![gnufied](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/ea666f/32.png) [@gnufied](https://www.ruby-forum.com/u/gnufied)\
**Post date:** [December 12, 2006, 12:30am UTC](https://www.ruby-forum.com/t/private-methods-in-ruby/79071/1 "2006-12-12T00:30:35Z")

</div>

##Won’t work method #1

class Foobar  
private  
def foo; p “Foobar”; end  
end

class Baz \< Foobar  
def blah; foo; end  
end

baz = Baz.new  
baz.foo

## Work method #2

class Foobar  
private  
def foo; p “Foobar”; end  
end

class Baz \< Foobar  
def blah; foo; end  
end

baz = Baz.new  
baz.blah

PickAxe2:

If a method is private, it may be called only within the context of  
the calling object—it is never possible to access another object’s  
private methods directly, even if the object is of the same class as  
the caller.

So what happens in Method#2, why foo can be easily called, when called  
from inside the class Baz? I mean, that method foo should be still  
bound to instance baz…so in which context foo gets called in  
Method#2.

---

<div class="post-metadata">

**Author:** ![gnufied](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/ea666f/32.png) [@gnufied](https://www.ruby-forum.com/u/gnufied)\
**Post date:** [December 12, 2006, 1:06am UTC](https://www.ruby-forum.com/t/private-methods-in-ruby/79071/2 "2006-12-12T01:06:45Z")

</div>

On Tue, 2006-12-12 at 08:28 +0900, hemant wrote:

> class Baz \< Foobar  
> private methods directly, even if the object is of the same class as  
> the caller.
> 
> So what happens in Method#2, why foo can be easily called, when called  
> from inside the class Baz? I mean, that method foo should be still  
> bound to instance baz…so in which context foo gets called in  
> Method#2.

I’ll take a stab at this…

since the instance/object baz is of class Baz, inherited from Foobar, it  
has the method foo. When you call baz.blah, baz internally calls its  
own foo method, which it is allowed to do.

the “even if the object is of the same class…” bit is a little  
confusing, but means that if you (somehow) link baz and baz2 (two  
different instances) they can’t call each others private methods, even  
though they are the same class.

hope that helps

Brian Broom
