Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

5
  • thanks for your explanations. i always get a little confused over what really happens on a circular require. at the moment it looks like this to me: on running b.rb, the parser encounters require 'a.rb and starts parsing a.rb. there it encounters require 'a.rb and, since b.rb has not been required yet, starts parsing b.rb. there is again a require 'a.rb, but a.rb has already been required, so it moves on in b.rb. at the end it executes B.calling, which tries to execute ::A.do_something. this fails because the parsing of a.rb has not yet been completed (or has been aborted comletely?) Commented Nov 11, 2011 at 19:35
  • Almost, I think the thing you are missing is that require only loads the file once. So it goes like this: Commented Nov 12, 2011 at 14:38
  • (oh, also keep in mind that running and parsing are essentially the same thing in Ruby). So on running b.rb, the parser encounters require 'a.rb' and starts parsing a.rb. The first thing encountered is require 'b.rb', but b.rb is already in the parser, so require 'b.rb' is ignored. The rest of a.rb defines module A, then we go to the rest of b.rb which defines module B and then runs B.calling (which works). However, if you start with a.rb instead of b.rb, things don't work. Commented Nov 12, 2011 at 15:01
  • running b.rb does not work! (it produces a NameError. however, running a.rb 'works', it produces 'doing..'). that's what confused me at first. i think running is different from requiring (try puts 'c'; require './c.rb' in a file named c.rb. if you run it, you get 'c' twice!), which is the main cause for this trouble. Commented Nov 12, 2011 at 20:44
  • 1
    Ah sorry, yes the require behavior is different. I edited the original answer to reflect this more accurately. Commented Nov 14, 2011 at 15:31