From: Stefano Crocco Date: 2008-07-23T22:02:24+09:00 Subject: Re: circular 'require' On Wednesday 23 July 2008, Shadowfirebird wrote: > *Is* there any executable code in my two example programs, other than > the "require"s? The short answer to your question is that in ruby everything is "executable code", including class and method definitions. The "executable code" Peter refers to is that code which is executed immediately when the script is required/loaded/called. This is any kind of code except that enclosed in method definitions and blocks. Code in method bodies is executed only when the method is called. Code in blocks is executed only when the block is called. All other code is executed as soon as it's seen. This explains why the line def self.testone(); Two.whoistwo; end in class One doesn't cause trouble: the body of the method won't be executed until the method is called. Until then, ruby has no interest in looking for a constant called Two. This greatly reduces the need of recursive requires: a class or constant need only to be defined when the code which uses it is actually executed, not when it is 'read'. Regarding why your code doesn't work, I think Peter is almost correct in his analisys, except when he states that the name of the file is stored in $" before being loaded, in the require case. After actually testing your code (which I should have done before sending my first mail), I went looking in the ruby source code to try to understand why the behavior I described wasn't the observed one. From what I understand (I'm not very good at reading C code), it seems that ruby has a mechanism which avoids exactly this kind of endless loop: when it starts requiring a file, it stores it in some kind of table (which as nothing to do with $"), where it remains until it's been 'fully' required (that is, until the code it contains, including other requires, has been executed). While the file is in the table, attempts to require it again fail, just as it had been put in $". Only at the end of this process, the file is added to $". For those interested, the involved C functions are rb_require_safe and load_lock, both in eval.c in the ruby distribution. Unfortunately, my skills haven't been enough to understand what happens when the file is given as a argument to ruby, rather than required. Sorry for the wrong information I gave before Stefano