How to Write a One-Line if in Ruby with Modifier if
When an if guards a single statement, Ruby lets you put the condition after it: puts 'It is hot.' if temperature > 30. It reads like a sentence and saves the three lines of a full if ... end.
Syntax
<statement> if <condition>
<statement> unless <condition>
| Part | What it does |
|---|---|
<statement> | Runs only when the test says so. |
if <condition> | Runs the statement when the condition is true. |
unless <condition> | Runs the statement when the condition is false. |
The Ruby control expressions documentation: "if and unless can also be used to modify an expression. When used as a modifier the left-hand side is the "then" statement and the right-hand side is the "test" expression".
The Example
The example has two one-line checks on a temperature of 34; only the first is true.
Prerequisites
- Ruby. This guide uses Ruby 4.0.10.
Step 1: Write the Code
Create a file named main.rb:

temperature = 34
puts 'It is hot.' if temperature > 30
puts 'Bring a coat.' if temperature < 10
Step 2: Run It
ruby main.rb
It is hot.

34 > 30 was true, so the first line printed; 34 < 10 was false, so the second didn't. The command is the same in zsh, bash and PowerShell.
The Opposite: unless
unless runs the statement when the condition is false: puts 'No coat needed.' unless temperature < 10 printed No coat needed.. It suits early exits too, as in abort 'Missing secret' if secret.empty?.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Adding else to a modifier | unexpected 'else', expecting end-of-input | Use a full if ... else ... end |
| Long statements with a modifier | The condition hides at the end of a long line | Use the full form when the statement is long |
unless with a negative condition, as in unless !ready | Double negatives are hard to read | Write if ready |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| A line never runs | The modifier's condition is false | Print the condition's value with p |
A syntax error near else | else after a modifier | Switch to the full if form |
FAQ
Is the condition checked before the statement runs?
Yes. Even though it's written last, the condition is evaluated first.
Can I use it with return?
Yes: return 'negative' if n < 0 is a common way to leave a method early.
Conclusion
statement if condition runs one statement when the condition is true, and statement unless condition when it's false. Use the full if ... end for longer code or an else.
Additional Resources
- Modifier if and unless, in the Ruby documentation.
