Forum

Learn Ruby If Then …
 
Notifications
Clear all

Learn Ruby If Then Else statements

1 Posts
1 Users
0 Reactions
11 Views
 josh
(@josh)
Member Admin
Joined: 2 months ago
Posts: 510
Topic starter  

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 (not else if or elif) 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.

 


   
Quote
Share: