Ruby - If-Else Condition

1. Introduction

In Ruby, if-else conditionals provide a way to execute different code based on whether a condition is true or false. There are several forms of this conditional, each tailored to specific scenarios.

Conditional Statements:

1. if statement: Executes a code block if a condition is true.

2. if-else statement: Executes one block of code if a condition is true, and another if it's false.

3. if-else-if (elsif) statement: For checking multiple conditions sequentially.

4. ternary statement: A shortened form of the if-else statement.

2. Program Steps

1. Initialize a sample variable.

2. Apply and demonstrate the common conditional methods on the initialized variable.

3. Code Program

# Initialize a sample variable
number = 15

# 1. if statement
if number > 10
  puts "The number is greater than 10."
end

# 2. if-else statement
if number.even?
  puts "The number is even."
else
  puts "The number is odd."
end

# 3. if-else-if (elsif) statement
if number < 10
  puts "The number is less than 10."
elsif number > 20
  puts "The number is greater than 20."
else
  puts "The number is between 10 and 20."
end

# 4. ternary (shortened if-else) statement
message = number > 0 ? "The number is positive." : "The number is non-positive."
puts message

Output:

The number is greater than 10.
The number is odd.
The number is between 10 and 20.
The number is positive.

Explanation:

1. The if statement checks a single condition and runs a code block if that condition is true.

2. The if-else statement checks a condition and runs the first block of code if the condition is true, and the second block if it's false.

3. The elsif allows for additional conditions to be checked if previous conditions are false. It stands for "else-if".

4. The ternary operator (? :) allows for a short form of the if-else statement, typically used for assignment based on a condition.


Comments