A
Antti Karanta
Hi!
I have been doing different things w/ Ruby for a couple of years now and
the only bad thing I can say about it is that it makes programming in other
languages feel awfully burdensome. = )
Anyhow, I really like how everything makes sense. There is one thing that
I have not been able to fit in entirely. A Ruby program starts in the
context of the "main" object,
antti@hyperion:~> ruby -e "puts self"
main
antti@hyperion:~> ruby -e "puts self.class"
Object
However, the methods I declare in the context of this "main" object are
somehow available as private methods of class Object (and naturally usable
from subclasses):
def foo
puts "hello"
end
class Bar
def amethod
foo
end
end
b = Bar.new
b.amethod
outputs:
hello
Is there some logical explanation for this? I understand that this is very
convenient as these methods appear as "stand-alone functions", but taking
it just as "it just is so" breaks the otherwise consistent rules, as
normally you have to define a method in the context of a class for it to be
a method of that class. However, the "main" object is not class Object, nor
is it a class at all:
antti@hyperion:~> ruby -e "puts self.kind_of?(Class)"
false
antti@hyperion:~> ruby -e "puts self.kind_of?(Module)"
false
So what is the logic behind the "main" object? Is there a logical reason
for the methods defined in its context to appear as private methods of
class Object?
-Antti-
I have been doing different things w/ Ruby for a couple of years now and
the only bad thing I can say about it is that it makes programming in other
languages feel awfully burdensome. = )
Anyhow, I really like how everything makes sense. There is one thing that
I have not been able to fit in entirely. A Ruby program starts in the
context of the "main" object,
antti@hyperion:~> ruby -e "puts self"
main
antti@hyperion:~> ruby -e "puts self.class"
Object
However, the methods I declare in the context of this "main" object are
somehow available as private methods of class Object (and naturally usable
from subclasses):
def foo
puts "hello"
end
class Bar
def amethod
foo
end
end
b = Bar.new
b.amethod
outputs:
hello
Is there some logical explanation for this? I understand that this is very
convenient as these methods appear as "stand-alone functions", but taking
it just as "it just is so" breaks the otherwise consistent rules, as
normally you have to define a method in the context of a class for it to be
a method of that class. However, the "main" object is not class Object, nor
is it a class at all:
antti@hyperion:~> ruby -e "puts self.kind_of?(Class)"
false
antti@hyperion:~> ruby -e "puts self.kind_of?(Module)"
false
So what is the logic behind the "main" object? Is there a logical reason
for the methods defined in its context to appear as private methods of
class Object?
-Antti-