Notifications
Clear all
Topic starter 01/08/2025 11:11 pm
Ruby’s if-then-else
statements are your go-to for decision-making logic—like telling your code, “If this is true, do that; otherwise, do something else.” Let’s break it down with style 🧠💎
🧪 Basic if
Statement
x = 10
if x > 5
puts "x is greater than 5"
end
- If the condition is true, the code inside runs.
- Ruby doesn’t require
then
, but you can use it for inline expressions.
🔄 Adding else
and elsif
x = 3
if x > 5
puts "x is greater than 5"
elsif x == 5
puts "x is equal to 5"
else
puts "x is less than 5"
end
elsif
(notelse if
orelif
) checks another condition.else
runs if none of the above are true.
🧠 Inline if-then-else
puts "x is big" if x > 5
Or even:
result = if x > 5 then "big" else "small" end
- Handy for short, one-liner decisions.
🧬 Bonus: unless
Statement
unless x > 5
puts "x is not greater than 5"
end
- Think of it as the opposite of
if
.