if / elsif / else
In this page:
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
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: