BEGIN and END Blocks In Ruby
Every Ruby source file can run as the BEGIN blocks when the file is being loaded and runs the END blocks after the program has finished executing. The BEGIN and END statements are different from each other. A program may contain multiple BEGIN and END blocks. If there is more than one BEGIN statement in a program, they are executed in the order If there is more than one END statement, they are executed in the reverse of the order. the first END one is executed last. An open curly brace always come after BEGIN and END keyword.
Syntax:
BEGIN{
Code
.
.
.}
END{
.
.
.}
Below is the example to better understand:
Example :
BEGIN {
puts "BEGIN code block"
}
END {
puts "END code block"
}
puts "GeeksForGeeks"
|
Output :
BEGIN code block
GeeksForGeeks
END code block
In above example, as we can see BEGIN block code will execute first then Main block code will be executed after that END block code will be executed.
Example :
BEGIN {
a = 4
b = 3
c = a + b
puts "This is BEGIN block code"
puts c
}
END {
a = 4
b = 3
c = a * b
puts "This is END block code"
puts c
}
puts "Main Block"
|
Output :
This is BEGIN block code
7
Main Block
This is END block code
12
Note :If an END statement is used in a loop Then it is executed more than once.
Last Updated :
25 Sep, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...