Menu
Coddy logo textTech

Nested If - Else

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

What if you need to check more than two conditions? You can place an if-else statement inside another if-else statement. This is called nesting, and it lets you handle multiple decision points.

score = 85

if score >= 90
  puts "Grade: A"
else
  if score >= 80
    puts "Grade: B"
  else
    puts "Grade: C"
  end
end

Ruby checks the first condition. If it's false, it moves to the else block where another if-else waits. This creates a chain of decisions, each narrowing down the possibilities.

Ruby provides a cleaner way to write this using elsif, which combines else and if into one keyword:

score = 85

if score >= 90
  puts "Grade: A"
elsif score >= 80
  puts "Grade: B"
else
  puts "Grade: C"
end

Both examples produce the same result, but elsif keeps your code flatter and easier to read. You can chain as many elsif conditions as you need, and the final else catches anything that doesn't match the previous conditions.

challenge icon

Challenge

Easy

You are provided with the following variable:

temperature = 15

Create a weather advisory system using if, elsif, and else to classify the temperature and print the appropriate message:

  • If temperature is greater than or equal to 30, print Hot - Stay hydrated
  • If temperature is greater than or equal to 20, print Warm - Enjoy the day
  • If temperature is greater than or equal to 10, print Cool - Bring a jacket
  • If temperature is greater than or equal to 0, print Cold - Bundle up
  • Otherwise, print Freezing - Stay indoors

Output only the single message that matches the temperature.

Cheat sheet

You can nest if-else statements inside each other to check multiple conditions:

score = 85

if score >= 90
  puts "Grade: A"
else
  if score >= 80
    puts "Grade: B"
  else
    puts "Grade: C"
  end
end

Ruby provides elsif as a cleaner way to chain multiple conditions:

score = 85

if score >= 90
  puts "Grade: A"
elsif score >= 80
  puts "Grade: B"
else
  puts "Grade: C"
end

You can chain as many elsif conditions as needed. The final else catches anything that doesn't match the previous conditions.

Try it yourself

temperature = 15

# TODO: Write your code below to classify the temperature
# Use if, elsif, and else to print the appropriate weather advisory message
quiz iconTest yourself

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

All lessons in Fundamentals