EZ

Eduzan

Learning Hub

Eduzan
Eduzan / Ruby

Ruby Control Statement

Computer Science / Ruby tutorial chapter - Published 2025-12-16 - Ruby

Decision-making in programming is much like making choices in real life. In a program, certain blocks of code are executed based on whether a specific condition is true or false. Programming languages use control statements to manage the flow of execution depending on these conditions. These control structures guide the direction of execution, causing the program to branch or continue based on the current state. In Ruby, the if-else structure helps in testing these conditions.

Types of Decision-Making Statements in Ruby:

1. if statement
2. if-else statement
3. if-elsif ladder
4. Ternary statement

1. if Statement: In Ruby, the if statement determines whether a block of code should be executed based on a condition. If the condition evaluates to true, the associated code is executed.

Syntax:

if (condition)
   # code to be executed
end

Example:

# Ruby program to demonstrate the if statement

temperature = 30

# Check if temperature is above 25 degrees
if temperature > 25
  puts "It's a warm day."
end

Output:

It's a warm day.

2. if-else Statement: The if-else statement is used when one block of code should be executed if the condition is true, and another block should run if the condition is false.

Syntax:

if (condition)
    # code if the condition is true
else
    # code if the condition is false
end

Example:

# Ruby program to demonstrate if-else statement

time = 16

# Check if the time is past noon
if time > 12
  puts "Good afternoon!"
else
  puts "Good morning!"
end

Output:

Good afternoon!

3. if-elsif-else Ladder: This structure allows multiple conditions to be evaluated one after another. Once a true condition is found, the corresponding block of code is executed, and the remaining conditions are skipped.

Syntax:

if (condition1)
    # code if condition1 is true
elsif (condition2)
    # code if condition2 is true
else
    # code if neither condition1 nor condition2 is true
end

Example:

# Ruby program to demonstrate if-elsif-else ladder

score = 85

if score < 50
  puts "You failed."
elsif score >= 50 && score < 65
  puts "You passed with a C grade."
elsif score >= 65 && score < 80
  puts "You passed with a B grade."
elsif score >= 80 && score < 90
  puts "You passed with an A grade."
else
  puts "You passed with an A+ grade."
end

Output:

You passed with an A grade.

4. Ternary Operator: The ternary operator is a shorthand for simple if-else statements. It evaluates a condition and returns one of two values based on whether the condition is true or false.

Syntax:

condition ? true_value : false_value

Example:

# Ruby program to demonstrate the ternary operator

age = 20

# Ternary operator to check if the person is an adult
status = (age >= 18) ? "Adult" : "Minor"
puts status

Output:

Adult
End of lesson.