Hello everyone!
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.
Yes
When I call puts, I don't specify a receiver, so self
is assumed (I think so).
Yes
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
Object?
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
'self':
irb(main):001:0> p self
main
=> nil
irb(main):002:0> puts "foo"
foo
=> nil
irb(main):003:0> self.puts "foo"
NoMethodError: private method `puts' called for main:Object
from (irb):3
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"
irb(main):006:1> nil
irb(main):007:1> end
=> nil
irb(main):008:0> bar
bar
=> nil
irb(main):009:0> self.bar
bar
=> nil
But
$ ruby -e'def bar;puts "bar";nil;end;bar;self.bar'
bar
-e:1: private method `bar' called for main:Object (NoMethodError)
Help would be greatly appreciated!
HTH
···
On 5/3/07, Lucas Holland <hollandlucas@gmail.com> wrote:
--
Rick DeNatale
My blog on Ruby
http://talklikeaduck.denhaven2.com/