How to Use If Else in Ruby: Simple Guide with Examples
In Ruby, use
if to run code when a condition is true, and else to run code when it is false. The syntax is if condition ... else ... end. This lets your program choose between two paths based on a condition.Syntax
The if else statement in Ruby lets you run different code depending on a condition. It starts with if followed by a condition, then the code to run if true. The else part runs if the condition is false. Always end with end.
- if condition: Checks if the condition is true.
- code: Runs if condition is true.
- else: Runs if condition is false.
- end: Closes the if else block.
ruby
if condition # code if true else # code if false end
Example
This example checks if a number is positive or not. It prints a message based on the condition.
ruby
number = 5 if number > 0 puts "The number is positive" else puts "The number is zero or negative" end
Output
The number is positive
Common Pitfalls
Common mistakes include forgetting the end keyword, mixing up if and else blocks, or using incorrect indentation which can confuse readers. Also, remember that Ruby treats nil and false as falsey, everything else is truthy.
ruby
wrong: if number > 0 puts "Positive" else puts "Not positive" # missing end correct: if number > 0 puts "Positive" else puts "Not positive" end
Quick Reference
| Keyword | Purpose |
|---|---|
| if | Starts the condition check |
| else | Runs code if condition is false |
| elsif | Checks another condition if first is false |
| end | Ends the if else block |
Key Takeaways
Use
if to run code when a condition is true and else when false.Always close your
if else block with end.Indent your code inside
if and else for clarity.Remember Ruby treats only
false and nil as falsey.Use
elsif for multiple conditions between if and else.