From: matt@... (matt neuburg) Date: 2009-03-16T02:57:40+09:00 Subject: Re: Basics of Require Mike Stephens wrote: > Ken Bloom wrote: > > > > def method > > require 'foo' > > end > > > > only loads 'foo' when you call the method. The contents of 'foo' are > > visible globally. (Unlike a #include in C) > > > > module Foo > > require 'foo' > > end > > > > class Foo > > require 'foo' > > end > > > > These are exactly the same. They both load 'foo', and the contents of > > 'foo' are NOT wrapped in the module or class Foo. > > I can't see the logic there. You're saying if the require is inside a > method, Ruby will not doing anything until your program calls that > method. However if the require is inside a class, Ruby will go and fetch > the code before you ever refer to that class? The thing to grok here that is a class or module definition is itself executable code. That, after all, is how the class gets defined! When you say: class MyClass end you really are executing code in order to bring the class into existence (the constant name is created, etc). When you think about it this way, you realize, aha! That's how stuff like attr works. A big hunk of the coolness of Ruby depends upon this very fact. class MyClass attr :howdy # executes right now! end Similarly if you say class MyClass puts "howdy" end ... then "howdy" is output as soon as this code is encountered. It is executable code. But a method definition just defines a method. So when you say: class MyClass def howdy puts "howdy" end end then "howdy" is not output, because all you did was define a method - you haven't called it yet. The "def" is executed right now (i.e. the method is indeed brought into existence) but its *contents* are not executed (though of course the interpreter is applied to them, to make sense of them). m. -- matt neuburg, phd = matt@tidbits.com, http://www.tidbits.com/matt/ Leopard - http://www.takecontrolbooks.com/leopard-customizing.html AppleScript - http://www.amazon.com/gp/product/0596102119 Read TidBITS! It's free and smart. http://www.tidbits.com