Ruby Logo

Ruby Conditionals & Decision Making

Master Ruby's conditional statements including if/else, elsif, and decision-making logic with comprehensive examples and interactive practice.

Home Ruby Ruby Conditionals & Decision Making

Ruby Conditionals & Decision Making

Master Ruby's conditional statements to make your programs intelligent and responsive. Learn how to create decision-making logic that responds to different situations and user inputs.

What are Conditionals?

Conditionals: Programming constructs that allow your code to make decisions and execute different actions based on whether certain conditions are true or false. Think of them as the "if-then" logic of programming.

Real-World Analogy

Think of conditionals like traffic lights: If the light is green (condition is true), you go. If it's red (condition is false), you stop. Your program makes similar decisions based on data, user input, or system state.

if/else Statements

if/else: The most fundamental conditional structure. Execute one block of code if a condition is true, another if it's false.

Basic if/else Structure

# Basic if/else structure
age = 18

if
age >= 18
puts "You are an adult"
else
puts "You are a minor"
end

# Output: "You are an adult"

Multiple Conditions with elsif

# Grade classification with multiple conditions
score = 85

if
score >= 90
puts "Grade: A - Excellent!"
elsif
score >= 80
puts "Grade: B - Good job!"
elsif
score >= 70
puts "Grade: C - Satisfactory"
elsif
score >= 60
puts "Grade: D - Needs improvement"
else
puts "Grade: F - Failed"
end

# Output: "Grade: B - Good job!"

Ternary Operator (Shorthand)

# Ternary operator: condition ? true_value : false_value
age = 20
status = age >= 18 ? "adult" : "minor"
puts
"You are an #{status}"

# Output: "You are an adult"

# More complex ternary example
temperature = 25
weather = temperature > 30 ? "hot" : temperature > 20 ? "warm" : "cool"
puts
"It's #{weather} today"

# Output: "It's warm today"

unless Statement

unless: Ruby's unique conditional that executes code when a condition is false. It's the opposite of if - use it when you want to check for the absence of something.

Basic unless Structure

# unless executes when condition is false
user_logged_in = false

unless
user_logged_in
puts "Please log in to continue"
end

# Output: "Please log in to continue"

# unless with else (equivalent to if not)
file_exists = true

unless
file_exists
puts "Creating new file..."
else
puts "File already exists"
end

# Output: "File already exists"

When to Use unless

  • Guard clauses: Check for error conditions early
  • Negative conditions: When the positive condition is harder to read
  • Validation: Check for missing or invalid data
  • Avoid complex unless: Don't use unless with complex conditions

case/when Statement

case/when: Ruby's switch statement equivalent. Perfect for handling multiple possible values of a single variable. Much cleaner than long if/elsif chains.

Basic case/when Structure

# Basic case/when for day of week
day = "Monday"

case
day
when
"Monday"
puts "Start of the work week"
when
"Friday"
puts "TGIF! Weekend is coming"
when
"Saturday"
,
"Sunday"
puts "Weekend! Time to relax"
else
puts "Regular work day"
end

# Output: "Start of the work week"

case with Ranges and Conditions

# case with ranges for age groups
age = 25

case
age
when
0..12
puts "Child"
when
13..19
puts "Teenager"
when
20..64
puts "Adult"
when
65..
puts "Senior"
end

# Output: "Adult"

# case with conditions (no value after case)
score = 85

case
when
score >= 90
puts "Excellent!"
when
score >= 80
puts "Good job!"
when
score >= 70
puts "Satisfactory"
else
puts "Needs improvement"
end

# Output: "Good job!"

Guard Clauses

Guard Clauses: Early returns that handle error conditions or edge cases first, making your code more readable and reducing nesting levels.

Without Guard Clauses (Nested)

# Nested conditionals - harder to read
def
process_user(user)
if
user
if
user.active?
if
user.email.present?
puts "Processing user: #{user.name}"
# Main logic here
else
puts "User has no email"
end
else
puts "User is inactive"
end
else
puts "No user provided"
end
end

With Guard Clauses (Clean)

# Guard clauses - much cleaner and readable
def
process_user(user)
return
puts
"No user provided"
unless
user
return
puts
"User is inactive"
unless
user.active?
return
puts
"User has no email"
unless
user.email.present?

# Main logic here - no nesting!
puts
"Processing user: #{user.name}"
end

Guard Clause Benefits

  • Reduced nesting: Flatter code structure is easier to read
  • Early returns: Handle edge cases first, then focus on main logic
  • Clear intent: Each guard clause states what's wrong clearly
  • Easier testing: Each condition can be tested independently

Advanced Conditional Patterns

Advanced Patterns: Ruby's flexible syntax allows for powerful conditional patterns that make code more expressive and concise.

Conditional Assignment

# Conditional assignment with ||= (or-equals)
name = nil
name ||= "Anonymous"
puts
name
# "Anonymous"

name = "John"
name ||= "Anonymous"
puts
name
# "John" (unchanged)

# Conditional assignment with &&= (and-equals)
user = { name: "Alice", email: "alice@example.com" }
user[:name] &&= user[:name].upcase
puts
user[:name]
# "ALICE"

Safe Navigation and Conditional Calls

# Safe navigation operator (&.)
user = nil
email = user&.email
puts
email
# nil (no error)

user = { email: "test@example.com" }
email = user&.email
puts
email
# "test@example.com"

# Conditional method calls
numbers = [1, 2, 3, 4, 5]
numbers.any? { |n| n > 3 } && puts "Found numbers greater than 3"
numbers.all? { |n| n > 0 } && puts "All numbers are positive"

Pattern Matching with case (Ruby 3.0+)

# Pattern matching with arrays
coordinates = [10, 20]

case
coordinates
in
[0, 0]
puts "At origin"
in
[x, 0]
puts "On x-axis at #{x}"
in
[0, y]
puts "On y-axis at #{y}"
in
[x, y]
puts "At position (#{x}, #{y})"
end

# Output: "At position (10, 20)"

Try It Yourself - Interactive Practice

Learning Tip: The best way to master conditionals is through hands-on practice! Try these examples and experiment with different conditions and values!

Interactive Code Runner

Ruby Code Editor
Output will appear here when you run the code...

Best Practices & Common Pitfalls

✅ Best Practices

  • Use guard clauses: Handle edge cases early with early returns
  • Prefer unless for negative conditions: Makes intent clearer
  • Use case/when for multiple values: Cleaner than long if/elsif chains
  • Keep conditions simple: Complex conditions should be extracted to methods
  • Use meaningful variable names: Make conditions self-documenting
  • Test edge cases: Always test boundary conditions
  • Use ternary for simple assignments: But avoid nested ternaries

❌ Common Pitfalls

  • Deep nesting: Avoid more than 2-3 levels of nesting
  • Complex unless conditions: unless with && or || is hard to read
  • Missing else clauses: Consider if you need to handle all cases
  • Overusing ternary: Don't sacrifice readability for brevity
  • Ignoring nil checks: Always consider nil values in conditions
  • Inconsistent style: Stick to one style throughout your codebase
  • Not testing edge cases: Test boundary values and nil conditions

Performance Considerations

  • Order conditions by frequency: Put most common conditions first
  • Use short-circuit evaluation: && and || stop evaluating when possible
  • Avoid expensive operations in conditions: Cache results if needed
  • Consider using case for multiple string comparisons: More efficient than multiple if/elsif

Conditional Mastery Checklist

Basic Conditionals

  • if/else statements
  • elsif for multiple conditions
  • Ternary operator (? :)
  • unless statements

Advanced Patterns

  • case/when statements
  • Guard clauses
  • Conditional assignment (||=, &&=)
  • Safe navigation (&.)

Best Practices

  • Clear, readable conditions
  • Avoid deep nesting
  • Use appropriate conditional type
  • Test edge cases thoroughly

Quick Navigation

Related Topics

Video Tutorial

Watch and learn ruby conditionals & decision making

Pro Tip: After reading through the content above, watch this video to reinforce your understanding and see the concepts in action!