iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

if / unless / case

Ruby’s conditionals double as expressions. if, unless, case, ternary, modifier-style suffixes — pick the form that reads cleanest.

if, unless, case patterns, postfix

EXAMPLE
age = 36

# 1) if / elsif / else as an expression
tier = if age >= 65
             'senior'
         elsif age >= 18
             'adult'
         else
             'minor'
         end

# 2) Postfix modifiers — perfect for guard clauses
puts 'overage' if age >= 18
return unless user.admin?
log.error('boom') if response.fail?

# 3) Ternary
label = age >= 18 ? 'adult' : 'minor'

# 4) case / when — equality, ranges, types, regex, custom matchers
grade =
    case score
    when 90..       then 'A'
    when 80..89    then 'B'
    when 70..79    then 'C'
    when 0..69     then 'F'
    else                'invalid'
    end

# 5) case on type
case value
when Integer  then puts "int #{value}"
when String   then puts "string of length #{value.length}"
when Symbol   then puts "symbol :#{value}"
when nil      then puts 'nil'
else               puts "other: #{value.class}"
end

# 6) Pattern matching (Ruby 3+) — case / in
result = { status: 200, body: { id: 42, name: 'Ada' } }
case result
in { status: 200, body: { id: Integer => id, name: String => name } }
    puts "ok #{id} #{name}"
in { status: 4.., body: { error: } }
    warn "4xx: #{error}"
in { status: 5.. }
    warn 'server error'
end

# 7) Ranges in case — the everyday workhorse
case status
when 200..299 then :success
when 300..399 then :redirect
when 400..499 then :client_error
when 500..599 then :server_error
end

# 8) unless — read “if not”
puts 'banned' unless user.active?

Why it matters

Pattern matching (case / in) was Ruby 3’s biggest language addition. For deeply nested API responses or hash destructuring, it’s noticeably cleaner than chained dig calls.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
n = 7
puts 'big' if n > 10
puts 'small' unless n > 10

case n
when 0..9   then puts 'digit'
when 10..99 then puts 'double'
else             puts 'big'
end
Try it Yourself »

Discussion

Loading…