What is a conditional in Ruby?

W

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.

Happy Programming!

About the author

Kelly Barkhurst

Designer to Fullstack is my place to geek out and share tech solutions from my day-to-day as a graphic designer, programmer, and business owner (portfolio). I also write on Arts and Bricks, a parenting blog and decal shop that embraces my family’s love of Art and LEGO bricks!

Add comment

By Kelly Barkhurst

Recent Posts

Archives

Categories