Control Flow in Ruby
Essential branching and looping constructs with readable idioms.
if / elsif / else
Conditions use truthiness: only false and nil are falsy; everything else is truthy.
if n > 0
:pos
elsif n == 0
:zero
else
:neg
end
Note: It’s elsif (one word), not else if.
unless and postfix modifiers
unless expresses negative conditions clearly. Postfix modifiers make short guards concise.
unless ready
prepare
end
do_something if ready
log("oops") unless ok
case / when
case uses === under the hood, enabling ranges, regexes, and class checks.
case status
when 200..299 then :ok
when 404 then :not_found
when /5\d\d/ then :server_error
when String then :string_input
else :error
end
Short‑circuit boolean control
Use && and || to guard or default values.
user && user.login! # only if user is truthy
name = input || "guest" # default if input is nil/false
Loops and iterators
Prefer iterators to manual loops; while/until exist when you need them. Control with break, next, and redo.
i = 0
while i < 3
puts i
i += 1
end
3.times { |k| puts k }
[1,2,3].each { |v| puts v }
1.upto(3) { |v| puts v }
Ternary and statement modifiers
Use ternary for small expression‑level choices; keep branches short. Modifiers keep guards succinct.
ok ? "yes" : "no"
puts("done") if ok
Summary
- Prefer iterators (
times,each,upto) over manual loops when possible - Use postfix modifiers and short‑circuiting for clear, concise control flow