Alan Coromano
Alan Coromano

Reputation: 26038

What does Ruby's BEGIN do?

What does BEGIN mean in Ruby, and how is it called? For example, given this code:

puts "This is sentence 1."

BEGIN {
  puts "This is sentence 2."
}

why is puts "This is sentence 2." executed first?

Upvotes: 13

Views: 3797

Answers (3)

tokhi
tokhi

Reputation: 21616

BEGIN and END Blocks

Every Ruby source file can declare blocks of code to be run as the file is being loaded (the BEGIN blocks) and after the program has finished executing (the END blocks).

BEGIN { 
   begin block code 
} 

END { 
   end block code 
}

A program may include multiple BEGIN and END blocks. BEGIN blocks are executed in the order they are encountered. END blocks are executed in reverse order.

You can find almost the same post in "Does begin . . . end while denote a 'block'?".

Read more about blocks on tutorialspoint

Upvotes: 4

the Tin Man
the Tin Man

Reputation: 160571

BEGIN and END set up blocks that are called before anything else gets executed, or after everything else, just before the interpreter quits.

For instance, running this:

END { puts 'END block' }

puts 'foobar'

BEGIN { puts 'BEGIN block' }

Outputs:

BEGIN block
foobar
END block

Normally we'd use a bit more logical order for the BEGIN and END blocks, but that demonstrates what they do.

Upvotes: 20

halfelf
halfelf

Reputation: 10107

From the Ruby docs for the BEGIN keyword:

BEGIN: Designates, via code block, code to be executed unconditionally before sequential execution of the program begins. Sometimes used to simulate forward references to methods.

Upvotes: 6

Related Questions