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 :

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby Program of BEGIN and END Block
  
BEGIN
   # BEGIN block code 
   puts "BEGIN code block"
  
END
   # END block code 
   puts "END code block"
}
   # MAIN block code 
puts "GeeksForGeeks"

chevron_right


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 :

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby Program of BEGIN and END Block
  
# BEGIN block 
BEGIN {
  
  a = 4
  b = 3
  c = a + b
        
   # BEGIN block code  
   puts "This is BEGIN block code"
   puts c
  
}  
    
# END block  
END {  
  
  a = 4
  b = 3
  c = a * b
        
   # END block code  
   puts "This is END block code"
   puts c
    
# Code will execute before END block  
puts "Main Block"

chevron_right


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.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.