Menu
Coddy logo textTech

If Statement

Part of the Fundamentals section of Coddy's Ruby journey — lesson 21 of 88.

Now that you know how to create boolean expressions using comparison and logical operators, it's time to make your programs actually do something based on those conditions. The if statement lets your code make decisions.

An if statement executes a block of code only when its condition evaluates to true. If the condition is false, the code inside is simply skipped:

age = 20

if age >= 18
  puts "You can vote!"
end

The structure is straightforward: the keyword if, followed by a condition, then the code to run, and finally end to close the block. The code between if and end only runs when the condition is true.

You can use any expression that returns a boolean, including logical operators:

temperature = 25
is_sunny = true

if temperature > 20 && is_sunny
  puts "Perfect day for a walk!"
end

When the condition is false, Ruby skips everything inside the block and continues with the rest of your program. This is how programs respond differently to different situations.

challenge icon

Challenge

Easy

You are provided with the following variables:

score = 85
temperature = 30
is_member = true
balance = 150
age = 21

Use if statements to check each condition below. If the condition is true, print the specified message. If the condition is false, print nothing for that check.

  1. If score is greater than or equal to 70, print Passed!
  2. If temperature is greater than 25 and is_member is true, print Pool access granted
  3. If balance is greater than 100 or is_member is true, print Eligible for discount
  4. If age is greater than or equal to 21 and balance is greater than 0, print Can make purchase

Each message should appear on its own line.

Cheat sheet

An if statement executes a block of code only when its condition evaluates to true:

age = 20

if age >= 18
  puts "You can vote!"
end

The structure consists of the if keyword, followed by a condition, the code to execute, and end to close the block.

You can use comparison and logical operators in the condition:

temperature = 25
is_sunny = true

if temperature > 20 && is_sunny
  puts "Perfect day for a walk!"
end

When the condition is false, Ruby skips the code inside the block.

Try it yourself

# Variables are already defined for you
score = 85
temperature = 30
is_member = true
balance = 150
age = 21

# TODO: Write your code below
# Use if statements to check each condition and print the appropriate message
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals