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?
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 .
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).
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With