From: Stefan Lang Date: 2005-09-24T20:47:03+09:00 Subject: Re: self.puts? On Saturday 24 September 2005 12:30, Derek Chesterfield wrote: > I am trying to convince myself that Ruby is fully OO [I'm not > suggesting it isn't!]. > > So writing 'object.method' sends a message 'method' to 'object', > and writing 'method' implies sending to self. So how come the > result of 'puts' is different to the result of 'self.puts'? > > > $ irb > > irb(main):001:0> puts "hello" > > hello > > => nil > > irb(main):002:0> self.puts "hello" > > NoMethodError: private method `puts' called for main:Object > > from (irb):2 > > I'm sure this is a semantic question, but I can't figure it out! > How come 'self.puts' find the private puts method of Object, > whereas 'puts' finds Kernel.puts? Both find the private method "puts", which is defined in the Kernel module. The Kernel module is included in the Object class. Ruby doesn't allow that a private method is called with an explicit receiver. If you write "self.puts", "self" is an explicit receiver. If you simply write "puts" the receiver is implicitly "self". Also try: $irb irb(main):001:0> class A irb(main):002:1> def foo irb(main):003:2> puts "hello, this is the foo method" irb(main):004:2> bar irb(main):005:2> self.bar irb(main):006:2> end irb(main):007:1> private irb(main):008:1> def bar irb(main):009:2> puts "hello, this is the bar method" irb(main):010:2> end irb(main):011:1> end => nil irb(main):012:0> a = A.new => # irb(main):013:0> a.bar NoMethodError: private method `bar' called for # from (irb):13 irb(main):014:0> a.foo hello, this is the foo method hello, this is the bar method NoMethodError: private method `bar' called for # from (irb):5:in `foo' from (irb):14 HTH, Stefan