The short answer would be: because Ruby is not Java or C++. The long answer is: in Ruby you can't invoke private methods by using explicit receiver: irb(main):001:0> class A irb(main):002:1> def m; puts 'ok' end irb(main):003:1> private :m irb(main):004:1> irb(main):005:1* def test irb(main):006:2> m irb(main):007:2> self.m irb(main):008:2> end irb(main):009:1> end => nil irb(main):010:0> A.new.test ok NoMethodError: private method `m' called for #<A:0x3331d0> from (irb):7:in `test' from (irb):10 from :0 irb(main):011:0> Kent. On 2/11/06, minkoo.seo / gmail.com <minkoo.seo / gmail.com> wrote: > Hi, all. > > I'm a somewhat newbie in ruby realm, and trying to write some codes. > Yesterday, I've found very strange characteristics in ruby. > > Please see the following: > > irb(main):001:0> class Foo > irb(main):002:1> private > irb(main):003:1> def bar > irb(main):004:2> print "hi" > irb(main):005:2> end > irb(main):006:1> end > => nil > irb(main):007:0> class Foo > irb(main):008:1> public > irb(main):009:1> def duh > irb(main):010:2> f = Foo.new > irb(main):011:2> f.bar > irb(main):012:2> end > irb(main):013:1> end > => nil > irb(main):014:0> f = Foo.new > => #<Foo:0x2cdd2f0> > irb(main):015:0> f.duh > NoMethodError: private method `bar' called for #<Foo:0x2cdb7a8> > from (irb):11:in `duh' > from (irb):15 > irb(main):016:0> quit > > As you can see in the above, method "bar" is private to Foo. And that > method is called from another public method "duh". "duh" calls private > method of "f", which is not the instance where "duh" is called. > > In all other languages, such as Java and C++, it is perfectly legal to > call private method as long as the method is called from methods of > the same class. > > For example, the following complies in C++: > > #include <iostream> > > using namespace std; > > class Foo > { > private: > void foo() > { > cout << "hi" << endl; > } > > public: > void duh() > { > Foo f; > f.foo(); > } > }; > > int main() > { > Foo f; > f.duh(); > return 0; > } > > I'm not saying that Ruby is wrong while the others are correct. I'm > just trying to figure out the "reason" of this strange behavior. Any > one can tell me? > > >