Menu
Coddy logo textTech

If - Else

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

Sometimes you need your program to choose between two different paths. The else keyword lets you specify what should happen when the if condition is false:

age = 15

if age >= 18
  puts "You can vote!"
else
  puts "You're too young to vote."
end

In this example, since age is 15, the condition age >= 18 is false, so Ruby skips the first block and runs the code after else instead. The program will output "You're too young to vote."

With if-else, exactly one of the two blocks will always run. If the condition is true, the first block executes. If it's false, the second block executes:

balance = 100
withdrawal = 150

if balance >= withdrawal
  puts "Withdrawal successful"
else
  puts "Insufficient funds"
end

This structure is perfect when you have two mutually exclusive outcomes. The program must go one way or the other, never both and never neither.

challenge icon

Challenge

Easy

You are provided with the following variables:

temperature = 35
has_umbrella = false
account_balance = 50
withdrawal_amount = 75
player_score = 100
high_score = 100

Use if-else statements to evaluate each scenario below. Print the appropriate message based on whether the condition is true or false.

  1. If temperature is greater than 30, print It's hot outside. Otherwise, print The weather is nice.
  2. If has_umbrella is true, print You're prepared for rain. Otherwise, print You might get wet.
  3. If account_balance is greater than or equal to withdrawal_amount, print Withdrawal approved. Otherwise, print Insufficient funds.
  4. If player_score is greater than high_score, print New high score!. Otherwise, print Try again.
  5. If temperature is less than 0 or temperature is greater than 40, print Extreme weather. Otherwise, print Normal conditions.

Each message should appear on its own line.

Cheat sheet

The else keyword specifies what should happen when the if condition is false:

age = 15

if age >= 18
  puts "You can vote!"
else
  puts "You're too young to vote."
end

With if-else, exactly one of the two blocks will always run. If the condition is true, the first block executes. If it's false, the second block executes:

balance = 100
withdrawal = 150

if balance >= withdrawal
  puts "Withdrawal successful"
else
  puts "Insufficient funds"
end

Try it yourself

# Variables are already defined for you
temperature = 35
has_umbrella = false
account_balance = 50
withdrawal_amount = 75
player_score = 100
high_score = 100

# TODO: Write your code below
# Use if-else statements to evaluate each scenario 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