Control Structures in Ruby

ruby-logo

In computer programing, control structures are used to control the flow of execution in a program. They are essential in any programming language. Ruby has several control structures, including if-else, switch-case, for loop, and while loop.

If-Else

The if-else structure is used to execute a block of code based on a condition. The if statement is used to check whether a condition is true or false. If the condition is true, the code inside the if block is executed. If the condition is false, the code inside the else block is executed.

Example:

age = 18
if age >= 18
  puts "You are eligible to vote."
else
  puts "You are not eligible to vote."
end

In the above example, a person’s age is checked to determine if they are eligible to vote or not.

Switch-Case

The switch-case structure is used to execute a block of code based on multiple conditions. It is also known as case-when in Ruby. The case statement is used to check the value of a variable against multiple conditions. If the value matches any of the conditions, the code inside the corresponding when block is executed.

Example:

day = "Monday"
case day
when "Monday"
  puts "Today is Monday."
when "Tuesday"
  puts "Today is Tuesday."
when "Wednesday"
  puts "Today is Wednesday."
else
  puts "Invalid day."
end

In the above example, the case statement checks the value of the variable day against multiple conditions to determine the day of the week.

For Loop

The for loop is used to execute a block of code a fixed number of times. It is also known as a numeric loop in Ruby. The for loop takes a range of values and executes the code inside the loop for each value in the range.

Example:

for i in 1..5
  puts i
end

In the above example, the for loop is used to print the numbers 1 to 5.

While Loop

The while loop is used to execute a block of code while a condition is true. The code inside the loop is executed repeatedly until the condition becomes false.

Example:

i = 1
while i <= 5
  puts i
  i += 1
end

In the above example, the while loop is used to print the numbers 1 to 5.

These are the different control structures available in Ruby. They can be used to write efficient and effective code. Control structures are an essential part of any program, and mastering them is crucial for any developer.

Total
0
Shares
Previous Post
ruby-logo

Operators: Overview of arithmetic, logical, and relational operators in Ruby programming language.

Next Post
ruby-logo

Functions: How to define and call functions in Ruby programming language, passing arguments, and returning values.

Related Posts