AnyCompiler

Control Flow

if/elsif/else, and its negated twin unless, work as you'd expect — but in Ruby they are expressions: the whole if...end block evaluates to a value, which can be assigned directly to a variable. No other control-flow-as-statement language on this site works this way quite so directly (Rust's if-as-expression is the closest relative, but Rust still requires matching types on every branch at compile time; Ruby requires nothing of the kind).

age = 20
message = if age >= 18
  "adult"
else
  "minor"
end
puts message

status = age >= 65 ? "senior" : "not senior"
puts status
Output
adult
not senior

What a real NoMethodError looks like

Because Ruby has no static type checker, calling a method an object doesn't actually have isn't caught until the line actually runs. This is the real diagnostic Ruby produces, captured from an actual run — not written to look plausible:

x = 5
x.fly_to_moon
Output
stderr
script.rb:2:in `<main>': undefined method `fly_to_moon' for 5:Integer (NoMethodError)

Ruby tells you exactly which object (5, an Integer) didn't understand which message (fly_to_moon) and exactly which kind of error that is (NoMethodError) — this is Ruby's duck typing cutting both ways: total flexibility about what any object can be asked to do, and a runtime (not compile-time) error the moment you ask for something it genuinely can't do. Next: loops and iterators — while, until, for, and why idiomatic Ruby almost always reaches for .times/.each instead.

Practice exercise

Given temp = 85, assign message using an if/elsif/else expression: "hot" if temp > 80, "warm" if temp > 60, otherwise "cold". Print message.