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:
Syntax
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
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
Login to try C/C++/Java/PHP code in the editor
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
- Writing
else ifinstead ofelsif, which needs an extraend. - Using
=instead of==in the condition, which assigns. - Forgetting
end, so the rest of the file is read as part of theifand a syntax error appears.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: