Phlip
3/15/2009 2:45:00 PM
Mike Stephens wrote:
> I don't have access to an instance of Ruby at the moment
You might ought to explain that one. It even runs on wrist watches these days!
> and I am not
> clear what is being said in The Ruby Programming Language (Flanagan &
> Matsumoto). It says require code is executed immediately. It also says
> you can't insert the require code in the middle of something as if you
> are copy-and-pasting, so can you explain some basics of what actually
> happens?
>
> If I have a file myprog.rb and libfile1.rb, and I run myprog:
>
> myprog1.rb========
> statement_1
> require libfile1
> ==============
>
> libfile1.rb=======
> statement_2
> ==============
>
> .. I believe Ruby will run statement 1 and then run statement 2
Ya.
>
> Now if I change this to:
>
> myprog2.rb========
> statement_1
> require libfile2
> ==============
>
> libfile2.rb=================
> Module Libfilemod
> statement_2
> end
> ======================
>
> ..I assume Ruby only runs statement 1 and stops
it runs statement_2 while compiling module Libfilemod.
> Now if I change myprog:
>
> myprog3=========
> statement_1
> def calllibfile
> require libfile1
> end
> ================
>
> ..well, can you do that? If you can, presumably Ruby reads libfile1 but
> doesn't execute it?
When you call calllibfile, the libfile1 gets evaluated and inserted into the
current environment (unless if someone else already required it).
However, the contents of libfile1 do not get inserted into the current scope
(inside calllibfile). They insert into the top-level context. This is so you can
delay requiring them, but get their symbols with the correct scope.
> Also does require get executed in the order of text encountered in the
> file or does the Ruby runtime pick out the keyword require up front and
> expand it before the native code?
The Ruby parser always runs top-to-bottom in each context
>
> myprog1.rb========
> statement_1
> require libfile1
> ==============
>
> libfile1.rb=======
> statement_2
> ==============
>
> Does this do 1 then 2 or 2 first?
You already asked that!
And get used to:
require 'libfile1'
require is nothing more than a method that takes a string. It's not a magic
keyword with its own parsing rules (like its equivalents are in certain other
languages.)
> What are the differences between wrapping require code in 'Module',
> 'Def' and 'Class'?
Nope - your tutorials cover that. Read on!
> The final question is in typical web environments like webrick, apache
> or eruby, does the require code get loaded and 'compiled' everytime any
> program refers to it or is there some mechanism to cache common code in
> 'compiled' form?
The second require simply does not happen (if the string argument is the same!).
So all the same symbols remain in the same Ruby environment.
--
Phlip