On 5/3/07, Lucas H. [email protected] 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).
In this case self refers to main, an instance
of Object, automatically created.
Yes, well it’s created when ruby starts up.
So, I’m really calling main.puts. main
is an instance of Object, so why is it able to call private methods of
You’re calling puts in the context of the top-level object. In other
words self is the top-level object in code which is outside any class
or method definitions. The method puts is a private instance method,
so any Object can invoke it as long as the receiver is implicitly
irb(main):001:0> p self
irb(main):002:0> puts “foo”
irb(main):003:0> self.puts “foo”
NoMethodError: private method `puts’ called for main:Object
Note that the ruby enforces private methods is that you can’t
explictily specify a receiver, even self.
Note that IRB treats methods defined at the top level a little
differently, in that they are public rather than private:
irb(main):004:0> def bar
irb(main):005:1> puts “bar”
$ ruby -e’def bar;puts “bar”;nil;end;bar;self.bar’
-e:1: private method `bar’ called for main:Object (NoMethodError)
Help would be greatly appreciated!
My blog on Ruby