0
0
Rubyprogramming~10 mins

If, elsif, else statements in Ruby - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - If, elsif, else statements
Start
Check if condition
|Yes
Execute if block
End
No
Check elsif condition
|Yes
Execute elsif block
End
No
Execute else block
End
The program checks the if condition first. If true, it runs the if block. If false, it checks the elsif condition. If that is true, it runs the elsif block. Otherwise, it runs the else block.
Execution Sample
Ruby
number = 7
if number < 5
  puts "Less than 5"
elsif number == 7
  puts "Equals 7"
else
  puts "Other number"
end
This code checks a number and prints a message depending on its value.
Execution Table
StepCondition CheckedCondition ResultBranch TakenOutput
1number < 5falseNo
2number == 7trueYesEquals 7
3elseN/ANo
💡 The elsif condition is true, so the elsif block runs and the rest is skipped.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
number7777
Key Moments - 2 Insights
Why does the else block not run even though it is present?
Because the elsif condition was true at step 2, the program runs that block and skips the else block, as shown in the execution_table row 2.
What happens if the first if condition is true?
If the first if condition is true, the program runs the if block and skips checking the elsif and else blocks, as shown by the flow in concept_flow.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output at step 2?
AEquals 7
BLess than 5
COther number
DNo output
💡 Hint
Check the 'Output' column in execution_table row 2.
At which step does the program decide to skip the else block?
AStep 1
BStep 2
CStep 3
DIt never skips the else block
💡 Hint
Look at the 'Branch Taken' column in execution_table rows 2 and 3.
If number was 3, which branch would run according to the execution flow?
Aelse block
Belsif block
Cif block
DNo block runs
💡 Hint
Refer to the condition 'number < 5' in execution_table step 1.
Concept Snapshot
if condition
  # code if true
elsif condition
  # code if elsif true
else
  # code if none true
end

Checks conditions in order and runs the first true block only.
Full Transcript
This visual execution shows how Ruby's if, elsif, else statements work. The program starts by checking the if condition. If it is true, it runs that block and skips the rest. If false, it checks the elsif condition. If that is true, it runs the elsif block and skips else. If none are true, it runs the else block. The example code checks if a number is less than 5, equals 7, or something else, and prints a message accordingly. The execution table traces each condition check and the branch taken. The variable tracker shows the number stays the same. Key moments clarify why else is skipped when elsif is true and what happens if the first if is true. The quiz tests understanding of output and flow decisions.