Open In App

BEGIN and END Blocks In Ruby

Improve
Improve
Like Article
Like
Save
Share
Report

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 :




# 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"


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 :




# 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"


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
Previous
Next
Share your thoughts in the comments
Similar Reads