From: Alex Gutteridge Date: 2008-07-23T20:18:58+09:00 Subject: Re: circular 'require' On 23 Jul 2008, at 10:48, Shadowfirebird wrote: > Hi, > > I'm new to ruby and I'm really enjoying it. However, there is one > thing... > > I gather from this list and my poor efforts that ruby does not like > files that 'require' each other circularly. I can find nothing in the > documentation about this, though; in fact, the description of require > seems to actually rule it out. Can anyone explain what is going on > here? > > (This happens in 1.8 and 1.9 and JRuby 1.0. So it's definitely me, > not Ruby, that has the problem.) > > > To flesh things out a little: > > 'require' is supposed to load files, unless they have been already > loaded. It stores an array of loaded files in $" for this purpose. > > Okay, suppose we have two programs in two different files: > > # test1.rb > require "test2.rb" > class One > def self.testone(); Two.whoistwo; end > def self.whoisone(); puts "class one"; end > end > > # test2.rb > require "test1.rb" > class Two > def self.testtwo(); One.whoisone; end > def self.whoistwo(); puts "class two"; end > end > >> ruby -w test1.rb > ./test1.rb:4: unititialized constant Two (NameError) > > Why does this happen? I would have thought that test1 would load > test2; then test2 would go to load test1 but find it already loaded. > Apparently what happens is that test2 doesn't get loaded at all. eh? Your example works fine for me on 1.8.6 unless I'm missing something? There also doesn't appear to be any mention of Two on line 4 of your test1.rb file, has something changed in the cut&paste? [alexg@powerbook]/Users/alexg/Desktop(25): cat test1.rb require "test2.rb" class One def self.testone(); Two.whoistwo; end def self.whoisone(); puts "class one"; end end [alexg@powerbook]/Users/alexg/Desktop(26): cat test2.rb require "test1.rb" class Two def self.testtwo(); One.whoisone; end def self.whoistwo(); puts "class two"; end end [alexg@powerbook]/Users/alexg/Desktop(27): ruby test1.rb [alexg@powerbook]/Users/alexg/Desktop(28): ruby test2.rb Also, I don't think Stefano's explanation can be quite right - if it went into an infinite loop as he describes you would never see an error message, it would just never end... Alex Gutteridge Department of Biochemistry University of Cambridge