Ruby is a general-purpose, dynamic, reflective, object-oriented programming language. Everything in Ruby is an object, except blocks, which procs and lambda have taken over. Creating a user interface between human programmers and the computer infrastructure that supports them was the aim of Ruby's development.
Procs and lambda: A lambda is an object in Ruby that is similar to a proc. A lambda, in contrast to a proc, accepts a specific number of arguments and returns to the caller method rather than exiting on its own.
As famously said, “ Every new beginning comes from another beginning's end.”
The same thing applied to programming.
To know what it is about, let's talk about Begin and End in ruby and how to do it in Ruby.
BEGIN and END in ruby fall under the main topic, Statement and Control Structure. Let us first understand what is statement and control structure.
Statement and Control Structure
Statements are declarations that can make up a line (or multiple lines). A statement in computer programming is a syntactic construct of an imperative programming language that expresses a course of action. A series of one or more statements make up a program written in this language. There could be internal parts to a statement (e.g., expressions).
Conditionals
The conditional is the most frequent control structure across all computer languages. Condition instructs the computer only to run a particular code when a specific condition is met or conditionally execute some code.
Ruby offers conditional expressions like ‘if’, ‘else’, ‘elsif’, and ‘return’ values.
Control Structures
Control statements regulate programs' execution depending on specific criteria to direct execution flow to advance and diverge in response to program state changes.
The if-else statement is used in Ruby to test the given condition similarly.
You can refer to our blog on code studio for control structures to read in detail. Now let’s move to the BEGIN and END.
BEGIN and END in Ruby
Ruby's reserved terms BEGIN and END(in uppercase) designate code to be executed at the start and end of a Ruby program, respectively.
In Begin, the statement executes the code of that specific block at the very beginning. In contrast, the execution of code and the ‘End’ statement runs some specific code at the last moment of performance.
Every Ruby source file can run both the BEGIN blocks when the file is loaded and the END blocks when the program is complete.
Multiple BEGIN and END blocks are possible in a program, and the END command is carried out at last.
Always provide an open curly brace’{’ after the BEGIN and END keywords. There are also some differences between the BEGIN and END statements. We will be exploring them all further(Note that the words BEGIN and END in capital letters differ significantly from those in lowercase if there are many).
They are executed in the sequence and the interpreter specifies in a program's BEGIN declaration confronts them.
If there are several END statements, they are all carried out in the first one instead of the sequence in which they are encountered.
Syntax
BEGIN and END must be followed by an open curly brace, Ruby code, and a close curly brace. Curly braces are required. Let's see with an example:
BEGIN
{
# Your code for executing in beginning
# Also used for Global initialization
}
END
{
# Your code to be executed at the end
# Also used for Global shutdown
}
You can also try this code with Online Ruby Compiler
# Ruby Program to demonstrate BEGIN and END Block
BEGIN {
# BEGIN block code is here
puts "This is the Beginning."
}
END {
# END block code is here
puts "This is the end."
}
# MAIN block code
puts "Welcome to Code studio."
You can also try this code with Online Ruby Compiler
In this piece of code, the first statement will execute first, because it is a BEGIN statement, then all the other code will get executed, and the end block will get executed at the end. We can see the same in the output below.
Output
Difference between BEGIN and END
Following is the comparison between BEGIN and END in Ruby:
BEGIN
END
The BEGIN block is performed before any definitions when you define something in it.
After all the codes have run, the END block will be performed.
If there are several BEGIN blocks, they are run one after the other.
Multiple END blocks are executed in reverse order if there are numerous END blocks.
You cannot share the other local variables since the BEGIN block has a local variable scope.
The variable scope is shared by the END block, not the BEGIN block. Therefore, you and the END block can share the local variable.
Code for Multiple BEGIN
As you can see, regardless of its position in the code or Ruby's regular top-down execution sequence, the BEGIN block executes at the beginning.
Multiple BEGIN blocks can also be used to separate sections of code. These blocks execute in the order they are defined in the code, meaning blocks defined earlier (higher up) in the source file execute first. Here's a simple example:
BEGIN {
puts "Hello"
# This will be printed
}
BEGIN {
puts "Ninjas"
# Also, this will be printed
}
BEGIN {
puts "Welcome to Code Studio"
# This will also be printed
}
You can also try this code with Online Ruby Compiler
As you can see in this code, regardless of the context in which it appears, the code associated with each of the three BEGIN statements will only run once. There won't be any defined variables outside of BEGIN blocks, and those that have been defined inside the block won't be visible outside.
Output
In the case of multiple end statements, the end statement written in the last will get executed first, as you can see in the below code:
Code for Multiple END
It is important to keep in mind that when utilizing multiple END blocks, they execute in the reverse order of their specification, meaning that the END blocks defined later (at the end of) the code run earlier. Here's a brief example:
END {
puts "Hello" # This will be printed
}
END {
puts "Ninja" # Also, this will be printed
}
You can also try this code with Online Ruby Compiler
In this code, there is two end statement, but we can see it is printing in LIFO order.
Output
Frequently Asked Questions
When to use BEGIN and END in Ruby?
Ruby's reserved keywords for the BEGIN and END blocks (both capitalized) are simple to employ. No matter where in the source file they are located, you can define certain code blocks to run at the start and end of your program's execution.
What is begin rescue in Ruby?
There is a likely exception in the code between "begin" and "rescue". The rescue block will go into action if an exception occurs.
What programming language uses begin to end?
Ruby's reserved terms BEGIN and END designate code to be executed at the start and end of a Ruby program, respectively.
Why do we use blocks in BEGIN and END in Ruby?
Ruby has closure-like structures called blocks, and they're central to the language. They can lessen repetition and possibly make coding less prone to errors when used appropriately.
What is binding in Ruby, and how is it used in the scope of BEGIN and END?
Ruby uses bindings, which capture the execution context at each location in the code to maintain track of the current scope. A Binding object that details the bindings at the current place is returned by the binding method.
Conclusion
In this blog, we have learned about statement and control Structure, specifically, BEGIN and END in Ruby, including Multiple BEGIN and END examples.
You can look at the following link to know Ruby in depth.