Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does Ruby's BEGIN do?

Tags:

ruby

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?

like image 905
Alan Coromano Avatar asked Dec 27 '12 06:12

Alan Coromano


People also ask

Can we use rescue without begin?

The method definition itself does the work of begin , so you can omit it. You can also do this with blocks. Now, there is one more way to use the rescue keyword without begin .

What does end do in Ruby?

END Designates, via code block, code to be executed just prior to program termination. END { puts "Bye!" } 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).

How do Ruby blocks work?

Ruby blocks are anonymous functions that can be passed into methods. Blocks are enclosed in a do-end statement or curly braces {}. do-end is usually used for blocks that span through multiple lines while {} is used for single line blocks. Blocks can have arguments which should be defined between two pipe | characters.

What is the difference between procs and blocks?

When using parameters prefixed with ampersands, passing a block to a method results in a proc in the method's context. Procs behave like blocks, but they can be stored in a variable. Lambdas are procs that behave like methods, meaning they enforce arity and return as methods instead of in their parent scope.


1 Answers

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.

like image 73
the Tin Man Avatar answered Nov 16 '22 02:11

the Tin Man