[[ warning : this is really simplified ]]
>>>>> "T" == Tobias Reif <tobiasreif / pinkjuice.com> writes:
T> What's the underlying concept here?
POLS :-)
Imagine that you are a beginner. Your first script probably will be
def tt
puts "Hello world"
end
tt
i.e. you define what you call a "global function" and call it. You are
happy because it work
Your second script is
def tt
puts "Hello world"
end
class A
def a
tt
end
end
A.new.a
At this step you create a new class, and you learn that to call the method
defined in this class you must first create an instance of this class.
i.e. 'class A' just create a class, this mean that self can't make
reference to an instance and fatally make reference to the class.
Because you still think that tt is a "global function", you call it in the
method A#a and you are happy because it work
In reality "global function" don't exist in ruby, and tt is just a private
method of Object.
Your first 2 scripts work because
* at toplevel, class is Object and self is an instance of Object
* Object is the root of the hierarchy (i.e. A inherit from Object)
Your third script probably will be to create a class method, and you'll
see that when ruby create a class it also create automatically a
metaclass. The instance methods are stored in the class, and the class
methods are stored in the metaclass. This is why you can have a class
method with the same name than an instance method.
Finally one day you'll write
a = A.new
class << a
def b
puts "b"
end
end
and you'll see that you can have also method specific to an object.
Guy Decoux