From: Lucas Holland Date: 2007-05-04T13:52:21+09:00 Subject: Re: Top-level Robert Klemme wrote: > On 03.05.2007 20:13, Lucas Holland wrote: >> I'm currently diving a bit deeper into Ruby and I've already asked this >> question in the IRC (the folks there have been great I think I'm getting >> it 50%). The question's about top-level methods: >> >> Let's take puts as an example. Puts is inside of the Kernel module, >> which gets mixed into the Object class. So essentially, it's a private >> method of Object. When I call puts, I don't specify a receiver, so self >> is assumed (I think so). > > Correct. > >> In this case self refers to main, an instance >> of Object, automatically created. So, I'm really calling main.puts. main >> is an instance of Object, so why is it able to call private methods of >> Object? > > Um, you explained it already: "puts" is an *instance* method of Object. > And since "main" is an instance of Object or one of its subclasses > (all classes are subclasses of Object!) it has method "puts". Basically > the method is only defined private in order to enforce a more function > like invocation: > > irb(main):001:0> self.puts "foo" > NoMethodError: private method `puts' called for main:Object > from (irb):1 > from :0 > irb(main):002:0> puts "foo" > foo > => nil > irb(main):003:0> > > Kind regards > > robert Hey, it's me again (this time I'm logged in ;-) ). I understand that puts is a private instance method of Object and that thus, all instances of Object have the method. I also understand that I can only call private methods if the receiver is self (by not specifying the receiver). So, in this instance, that's the case. When I however create a class like so: class MyClass private def test puts "hello, world" end public def pub test end end I am able to call the test method because of the implicit receiver, self. In this case, however, self refers to the class MyClass (which is an instance of Class, as far as I know). But MyClass is an instance of Class, not of itself, so why can it suddenly call *instance* methods of itself? Thanks in advance, Lucas -- Posted via http://www.ruby-forum.com/.