BEGIN & END blocks

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?

Testes with two verion of ruby:
gus@comp tests]$ ruby -v
ruby 1.8.1 (2004-04-05) [i686-linux]
[gus@comp tests]$ /usr/local/bin/ruby -v
ruby 1.9.0 (2004-05-21) [i686-linux]

Guillaume.

Guillaume Marcais wrote:

[...] But that one is run and not the other is strange, isn't it?

ruby 1.8.1 (2004-04-05) [i686-linux]
[gus@comp tests]$ /usr/local/bin/ruby -v
ruby 1.9.0 (2004-05-21) [i686-linux]

Also:
  ruby 1.6.7 (2002-03-01) [i586-mswin32]

if false
  BEGIN { puts '*BEGIN*' }
  END { puts '* END *' }
end

puts 'Main'

#=> *BEGIN*
#=> Main

daz

Hi --

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

···

On Tue, 8 Jun 2004, Guillaume Marcais wrote:

--
David A. Black
dblack@wobblini.net