Hi --

On Tue, 8 Jun 2004, Guillaume Marcais wrote:

> I find this behavior of the BEGIN and END block to be rather strange:
> 
> 
> 
> [gus@comp tests]$ cat BEGIN.rb
> #! /usr/bin/ruby
> 
> BEGIN { puts("General begin") }
> END { puts("General end") }
> 
> puts("Main")
> 
> if $0 == __FILE__
>   BEGIN { puts("Protected begin") }
>   END { puts("Protected end") }
> end
> 
> [gus@comp tests]$ ruby BEGIN.rb
> General begin
> Protected begin
> Main
> Protected end
> General end
> 
> So far, so good.
> 
> [gus@comp tests]$ cat test_BEGIN.rb
> load 'BEGIN.rb'
> [gus@comp tests]$ ruby test_BEGIN.rb
> General begin
> Protected begin
> Main
> General end
> 
> There I don't understand. The behavior I was expected is that none of
> the 'protected' blocks would be run. A behavior I could understand is
> that both of them are run. But that one is run and not the other is
> strange, isn't it?

I believe that BEGIN blocks are run before any other program logic at
all, whereas END blocks are not, because it's possible for other logic
to intervene:

$ cat beg.rb
if false
  BEGIN { puts "BEGIN in 'if false' clause" }
  END   { puts "END in 'if false' clause" }
end

if true
  BEGIN { puts "BEGIN in 'if true' clause" }
  END   { puts "END in 'if true' clause" }
end

$ ruby -v beg.rb
ruby 1.8.1 (2003-12-25) [i686-linux]
BEGIN in 'if false' clause
BEGIN in 'if true' clause
END in 'if true' clause


David

-- 
David A. Black
dblack / wobblini.net