If, Unless, and Conditionals
Branching logic in Ruby, including the modifier form and unless -- two things most languages don't have.
2 min read
Ruby's conditionals will look familiar if you've used any C-family language, but Ruby adds a couple of readable shortcuts worth knowing from the start.
The basic if/elsif/else
age = 20
if age < 13
puts "child"
elsif age < 20
puts "teenager"
else
puts "adult"
end
Note there are no parentheses around the condition and no curly braces around the body — Ruby uses end to close the block instead. elsif (not else if) is the correct keyword; misspelling it as elseif is a common typo coming from other languages.
if as an expression
Like in Kotlin, if in Ruby returns a value, so you can assign the result directly instead of assigning inside each branch:
# Works, but repetitive
if age < 20
category = "young"
else
category = "adult"
end
# Better: if is an expression
category = age < 20 ? "young" : "adult"
category = if age < 20 then "young" else "adult" endThe ternary (condition ? a : b) is the idiomatic choice for simple two-way branches; a multi-line if assigned to a variable reads better once there are more than two branches.
unless: if's negated twin
unless condition runs its body when the condition is falsy — it's exactly if !condition, spelled to read naturally:
unless user.admin?
puts "Access denied"
end
# equivalent to:
if !user.admin?
puts "Access denied"
endunless reads well for simple, single negative conditions ("unless logged in," "unless empty"). It gets confusing fast with else or compound conditions — unless a && b forces the reader to mentally negate a boolean expression, which is exactly the kind of double-negative that slows people down. If you need else, or the condition has &&/|| in it, switch to if !(...) instead.
Modifier form
For a single statement guarded by a condition, Ruby lets you skip if/end entirely and put the condition after the statement:
puts "Negative!" if number < 0
return nil unless userThis modifier form is idiomatic Ruby for simple guard clauses — you'll see it constantly in real code, especially for early returns at the top of a method.
Truthiness recap
Remember from the data types lesson: only false and nil are falsy. Every condition here — if, unless, the ternary — follows that same rule, so if 0 and if "" both take the truthy branch.
count = 0
puts "has items" if count # prints -- 0 is truthy, this isn't checking count > 0
puts "has items" if count > 0 # correct way to check for a positive countThat last example is a genuinely common bug for people who assume Ruby treats 0 like C or JavaScript does.
Test what you just learned
4 quick questions. Get all of them right to unlock the next lesson.
You can take the quiz without an account — logging in just lets your result count toward your progress.