← Back to Ruby Course | Chapter 6: Control Flow | Lesson 1 of 7

if / elsif / else

In this page:

  1. if / elsif / else

if / elsif / else

An if statement runs its block only when the condition is truthy, elsif chains additional conditions, and else handles everything else, ending with end. Ruby also supports a trailing modifier form, puts "hi" if condition, for simple single-line conditionals. Unlike many languages, if itself is an expression in Ruby and returns a value.

Note: Since if is an expression, you can write result = if condition then a else b end to assign its value directly.

Example: if / elsif / else

markup
score = 85

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

puts "High score!" if score > 80
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.