How to Use Inline If in Ruby: Simple Syntax and Examples
In Ruby, you can use an inline
if by placing the condition after the statement, like puts 'Hello' if true. This runs the statement only if the condition is true, making your code concise and easy to read.Syntax
The inline if in Ruby lets you write a condition after a statement. It looks like this:
statement if condition
Here, statement runs only when condition is true.
ruby
puts 'Hello' if true puts 'World' if false
Output
Hello
Example
This example shows how to print a message only if a number is positive using inline if.
ruby
number = 5 puts 'Number is positive' if number > 0 number = -3 puts 'Number is positive' if number > 0
Output
Number is positive
Common Pitfalls
One common mistake is putting the if before the statement, which is not inline syntax. Also, avoid complex expressions inline as it hurts readability.
ruby
puts 'Hello' if true # Correct inline if if true then puts 'Hello' end # Incorrect inline if syntax
Output
Hello
Quick Reference
| Usage | Description |
|---|---|
| statement if condition | Runs statement only if condition is true |
| statement unless condition | Runs statement only if condition is false |
| statement if condition1 && condition2 | Runs statement if both conditions are true |
Key Takeaways
Use inline if by placing the condition after the statement for concise code.
Inline if runs the statement only when the condition is true.
Avoid complex logic in inline if to keep code readable.
Remember the syntax:
statement if condition.Use
unless inline for the opposite condition.