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

if / elsif / else

if, elsif, and else let a program choose between paths, like 'if it is cold wear a coat, else if it is rainy take an umbrella, else wear a t-shirt'. Ruby runs the first block whose question is true.

In this page:

  1. if / elsif / else
Syntax
ruby
if condition
  # body
elsif other_condition
  # body
else
  # body
end

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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Writing else if instead of elsif, which needs an extra end.
  2. Using = instead of == in the condition, which assigns.
  3. Forgetting end, so the rest of the file is read as part of the if and a syntax error appears.
🔒

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.