Conditionals (if, unless & case)
Conditionals control the branch paths of execution based on boolean checks. Ruby provides clean readability options like the unless keyword and statement modifiers.
1 Unless Keywords & Statement Modifiers
Ruby conditionals include readability-focused enhancements:
- unless Statement: The exact opposite of an `if` statement. Executes code blocks only if a condition evaluates to **false**: `unless user.logged_in? { login }`.
- Statement Modifier Shorthand: You can append conditionals to the end of a single-line expression to write cleaner, more readable code: `puts "Welcome" if user.admin?`.
2 Conditional Codes
Let's run a program evaluating conditions and checking unless clauses:
Ruby — Conditionals
▶ Run Code
score = 85
# Standard if-elsif structure
if score >= 90
puts "Grade: A"
elsif score >= 80
puts "Grade: B"
else
puts "Grade: F"
end
# Unless clause
is_admin = false
unless is_admin
puts "Access restricted to admins!"
end
# Statement Modifier
is_member = true
puts "Discount Applied!" if is_member
3 Code Challenge
Challenge: Write a script using a `case` statement (with `when` and `else`) that evaluates an integer rating (1-5) and outputs descriptive feedback for each score.