Ruby: Control flow – code examples
if / elsif / else
Use case: React differently, e.g. for grades, price tiers or access rights.
punkte = 73
if punkte >= 90
puts "excellent"
elsif punkte >= 70
puts "good"
else
puts "needs improvement"
endNo parentheses around the condition, the block ends with end. The further branch is called elsif. Only nil and false count as falsy.
Loops with times and each
Use case: Process every element of a list or repeat n times.
3.times { |i| puts "Round #{i}" }
["Apple", "Pear"].each do |frucht|
puts frucht
endRuby uses iterators with blocks instead of counting loops: times repeats, each runs over the elements. { } for single-line blocks, do ... end for multi-line ones.
case / when with Ranges and Classes
Control flow#case#when#range#regex
Use case: Classify input, e.g. age groups, file types or HTTP status codes.
def klasse(wert)
case wert
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 [0, 5, 42, "123", :a, nil, 12.5].map { |w| klasse(w) }.join(", ")when uses ===: values, ranges, classes and regexes match. Output: zero, single digit, whole number, number string, Text, nothing, unknown.