Martin DeMello
3/21/2005 9:58:00 AM
Ilias Lazaridis <ilias@lazaridis.com> wrote:
>
> > # one-pass interpreter, and you can reopen classes
> > # so let's just continue
>
> [sidenote: I don't understand this]
The ruby interpreter is one-pass insofar as it takes a single pass through
the file, from top to bottom, building and executing an abstract syntax tree
as it goes. Anything enclosed in a def...end block (and a few other
delayed-evaluation constructs like lambda) gets converted into a 'callable'
block of code, the rest is just executed. That's how attr_accessor works,
incidentally - it's just a piece of code that runs inside a class's context
and generates methods when it's executed. Try the following:
class Foo
def say_hello
puts "hello world"
end
puts "hi, this is the reader"
end
a = Foo.new
a.say_hello
the first puts statement gets executed when say_hello is called; the second
one is not inside a def statement, and so gets executed when the interpreter
gets to it.
Hence the lack of a main() method - in a sense, the whole fine is a main(),
since the entry point is the top of the file (comes in real handy when
writing quick imperative scripts - you aren't forced to define a class just
because Ruby is a pure OO language).
Hence the if __FILE__ == $0 blocks - if the file is not being run directly,
the condition fails, and the whole block is skipped.
As for reopening classes, you can modify a class at runtime (add/delete
methods, mix in a module), and any objects belonging to the class inherit
those modifications (rather trivially, since they look up methods in the
class). But, since this is a one pass interpreter, those changes come into
effect at the time the reader reads them, and so the object "changes" in the
middle of its lifecycle.
martin