At its simplest form, a conditional in Ruby is the code that starts with “if” and finishes with “end.”
A conditional statement groups the code between the if and end together into a unit of code that could become skippable.
Ruby executes code by moving line-by-line from top to bottom. A conditional statement requires that the if statement is true to run the code between the if and end. When the if statement is not true, that chunk of code is skipped, and Ruby begins executing on the following line after the end declaration.
Example of executing a conditional
INPUT
year = 2021
if year > 2020
puts "You've socially distanced."
end
OUTPUT
You've socially distanced.
Note: the value of year is 2021, which is greater than 2020, so this conditional is run.
Example of skipping a conditional
INPUT
year = 2018
if year > 2020
puts "You've socially distanced."
end
Note: the value of year is 2018, which is less than 2020, so this conditional is skipped.
OUTPUT
Note: the output is blank.
If you found this post helpful, then you might enjoy my other posts about Ruby basics and my experiences in a coding Bootcamp.