Menu
Coddy logo textTech

Inline if / unless

Part of the Logic & Flow section of Coddy's Ruby journey — lesson 41 of 56.

Ruby lets you put if and unless at the end of a single statement, as a one-line modifier. It reads almost like English.

puts "Adult" if age >= 18
puts "Save your work" unless saved

This is the same as:

if age >= 18
  puts "Adult"
end

unless saved
  puts "Save your work"
end

The inline form shines for guard-style checks at the top of a method, or for one-off conditional updates inside a loop:

return if name.nil? || name.empty?

counts = Hash.new(0)
words.each do |w|
  counts[w] += 1 unless w.start_with?("#")
end

Like the ternary, use inline modifiers for short statements. If the body would be more than a single line, write a real if block instead.

challenge icon

Challenge

Easy

Read a comma-separated list of integers. For each number, print one line, but only when the number is non-zero:

  • Print positive: <n> if n > 0
  • Print negative: <n> unless n >= 0

Both lines must use the inline modifier form (no if block, no else). After the loop, print Skipped zeros: <count>, where the count is the number of zeros, also computed without an if block (use count).

For input 3,-2,0,5,0, the output is:

positive: 3
negative: -2
positive: 5
Skipped zeros: 2

Cheat sheet

Ruby allows if and unless as inline modifiers at the end of a single statement:

puts "Adult" if age >= 18
puts "Save your work" unless saved

Useful for guard clauses or simple conditional updates:

return if name.nil? || name.empty?

counts[w] += 1 unless w.start_with?("#")

Use inline modifiers only for single-line bodies; use a full if block for anything longer.

Try it yourself

numbers = gets.chomp.split(",").map(&:to_i)

# TODO: print using inline `if` / `unless` for each number
# TODO: print Skipped zeros: <n> using count
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow