typestar

Conditionals in Ruby

if, elsif, unless and the one-line modifiers that read like prose.

score = 87

if score >= 90
  puts "gold"
elsif score >= 80
  puts "silver"
else
  puts "bronze"
end

# statement modifiers read like prose for one-line branches
puts "passed" if score >= 60
puts "retake" unless score >= 60

grade = score >= 80 ? "high" : "low"
puts grade

How it works

  1. A classic if/elsif/else ladder picks a medal tier.
  2. Statement modifiers put the condition after the action.
  3. unless flips the test; the ternary handles tiny either-ors.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
265
Tokens
62
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 39 seconds.

Type this snippet

Step 1 of 3 in Control flow, step 7 of 29 in Language basics.

← Previous Next →

Conditionals in other languages