Skip to content
If, Unless, Case
step 1/5

Reading — step 1 of 5

Learn

~1 min readControl Flow

if/elsif/else/end. The then keyword is optional. Ruby also has unless as a positive way to write if not:

if x > 0
    puts "positive"
elsif x < 0
    puts "negative"
else
    puts "zero"
end

puts "go!" unless ready_to_quit

Any if/unless can be appended as a modifier — useful for short guard statements:

puts "too low" if score < 60
return unless valid?

case/when is Ruby's pattern-match-y conditional. The when clauses use ===, which makes ranges and classes work naturally:

case score
when 90..100 then 'A'
when 80...90 then 'B'
else 'F'
end

In Ruby, only false and nil are falsy. EVERYTHING else (including 0, '', empty array) is truthy.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…

If, Unless, Case — Ruby Fundamentals