Skip to main content

How to Write a One-Line if in Ruby with Modifier if

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

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​

Syntax
<statement> if <condition>
<statement> unless <condition>
PartWhat 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:

main.rb, which sets temperature to 34, puts It is hot. if temperature > 30, and puts Bring a coat. if temperature < 10.

main.rb
temperature = 34

puts 'It is hot.' if temperature > 30
puts 'Bring a coat.' if temperature < 10

Step 2: Run It​

Terminal
ruby main.rb
Output
It is hot.

A zsh terminal where ruby main.rb prints 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​

MistakeWhat happensDo this instead
Adding else to a modifierunexpected 'else', expecting end-of-inputUse a full if ... else ... end
Long statements with a modifierThe condition hides at the end of a long lineUse the full form when the statement is long
unless with a negative condition, as in unless !readyDouble negatives are hard to readWrite if ready

Troubleshooting​

SymptomLikely causeFix
A line never runsThe modifier's condition is falsePrint the condition's value with p
A syntax error near elseelse after a modifierSwitch 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​