RbRuby
BeginnerLesson 3 of 16

Conditions: if, unless, case – Ruby

Deciding with if/elsif/else, the modifier form and the powerful case/when.

if needs no parentheses around the condition and ends with end. The further branch is called elsif (without an e).

punkte = 73
if punkte >= 90
  note = "excellent"
elsif punkte >= 70
  note = "good"
else
  note = "needs improvement"
end
puts note

if is an expression and returns a value. Shorthand forms: the modifier (... if condition), unless (the opposite of if) and the ternary operator.

alter = 20
status = alter >= 18 ? "adult" : "minor"
puts status
puts "Welcome!" if alter >= 18
puts "No entry" unless alter >= 18
note = if punkte >= 70 then "good" else "borderline" end
puts note

case/when compares using the === operator. That is why not only values match, but also ranges, classes and regular expressions:

def beschreibe(x)
  case x
  when 0 then "zero"
  when 1..9 then "single digit"
  when Integer then "whole number"
  when /^\d+$/ then "number string"
  when String, Symbol then "Text"
  when nil then "nothing"
  else "unknown"
  end
end

puts beschreibe(0), beschreibe(5), beschreibe(42), beschreibe("123")
puts beschreibe(:a), beschreibe(nil), beschreibe(12.5)

Truthiness works differently in Ruby than in many languages: only nil and false are falsy, everything else is truthy.

puts "0 is truthy" if 0
leer = ""
puts "empty string is truthy" if leer
puts "nil is falsy" unless nil

name = nil
puts(name || "Guest")       # Guest
puts name&.upcase.inspect  # nil  (&. = safe navigation)
x = nil
x ||= 10                   # only assign if nil/false
puts x
WarningUnlike in Python, PHP or JavaScript, 0 is truthy and so is "". Only nil and false are falsy.