From: Stefano Crocco Date: 2008-02-10T22:08:35+09:00 Subject: Re: Private encapsulation question Alle Sunday 10 February 2008, andrea ha scritto: > Hello, > I am trying to improve my understanding of encapsulation but I can't > understand the reason why the last 2 method calls in the following code > produce different results (cut and paste in irb, plus return key): > > class N > def initialize(n) > @number=n > end > > def self_n_wrapper > self.n > end > > def n_wrapper > n > end > > private > > def n > @number > end > > end > > a=N.new(8) > a.n_wrapper > a.self_n_wrapper > > > Thanks for help > Andrea Ruby implements private methods forbidding to call them with an explicit receiver, but only with the explicit receiver, self. This is enough to ensure a private instance method of class A can't be called by, for example an instance method of class B, because in the latter self is an instance of class B, not of class A. For a similar reason, you can call that method from an instance method of a class C derived from A. A side effect of this approach is that you can't call a private method using the explicit receiver self, even if self.my_method is the same as my_method I hope this helps Stefano