Ruby Conditional Statements

This chapter explores ruby-conditional-statements , which allow the execution of code based on specific conditions. Conditional statements form the foundation of decision-making in Ruby programs and enable dynamic behavior.

Chapter Goals

  • Understand the purpose and usage of conditional statements in Ruby.
  • Learn about if, unless, case, and ternary operator constructs.
  • Explore the use of nested and chained conditions.
  • Implement best practices for writing clear and efficient conditional logic.

Key Characteristics of Ruby Conditional Statements

  • Boolean Logic: Conditions evaluate to true or false.
  • Flexible Constructs: Support for multiple conditional keywords (if, unless, case).
  • Short-Circuiting: Logical operators in conditions stop evaluation as soon as the result is determined.
  • Readability: Encourages writing clean and expressive conditions.

Basic Rules for Conditional Statements

  • Use if for conditions that need to execute when true.
  • Use unless for conditions that need to execute when false.
  • Use case for multiple value comparisons.
  • Avoid deeply nested conditions for better readability.

Best Practices

  • Prefer meaningful variable names to clarify conditions.
  • Use parentheses for complex expressions to improve readability.
  • Avoid redundant conditions and simplify logic wherever possible.
  • Document non-trivial conditions to ensure maintainability.
  • Test edge cases to ensure correct behavior in all scenarios.

Syntax Table

Serial No Statement/Operator Syntax/Example Description
1 if Statement if condition \n code \n end Executes code if the condition is true.
2 unless Statement unless condition \n code \n end Executes code if the condition is false.
3 elsif Clause if condition \n code \n elsif other_condition \n code \n end Adds additional conditions to an if block.
4 else Clause if condition \n code \n else \n code \n end Executes code if no conditions are true.
5 case Statement case variable \n when value \n code \n else \n code \n end Compares a variable to multiple values.
6 Ternary Operator condition ? true_code : false_code Short form for if-else.

Syntax Explanation

1. if Statement

What is an if Statement?

The if statement executes code only when a specified condition evaluates to true.

Syntax

if condition

  code

end

Detailed Explanation

  • The code inside the block runs only if the condition evaluates to true.
  • Multiple conditions can be combined using logical operators (&&, ||).
  • Nested if statements can evaluate additional conditions when the outer condition is true.
  • Supports single-line if syntax for short conditions: puts “Eligible” if age >= 18.

Example

age = 18

if age >= 18

  puts “You are eligible to vote.”

end

Example Explanation

  • Checks if age is greater than or equal to 18.
  • Outputs “You are eligible to vote.” if the condition is true.

2. unless Statement

What is an unless Statement?

The unless statement executes code only when a specified condition evaluates to false.

Syntax

unless condition

  code

end

Detailed Explanation

  • The code inside the block runs only if the condition evaluates to false.
  • Useful for checking negative conditions.
  • Supports inline syntax for brevity: puts “Underage” unless age >= 18.

Example

age = 16

unless age >= 18

  puts “You are not eligible to vote.”

end

Example Explanation

  • Checks if age is less than 18.
  • Outputs “You are not eligible to vote.” if the condition is false.

3. elsif Clause

What is an elsif Clause?

The elsif clause allows checking additional conditions within an if block.

Syntax

if condition

  code

elsif other_condition

  code

end

Detailed Explanation

  • Adds additional conditions to an if block.
  • Stops checking conditions as soon as one evaluates to true.
  • Enables multi-condition logic without deeply nested if statements.
  • Can include multiple elsif clauses in a single block.

Example

score = 75

if score >= 90

  puts “Grade: A”

elsif score >= 75

  puts “Grade: B”

else

  puts “Grade: C”

end

Example Explanation

  • Checks if score meets multiple thresholds and outputs the appropriate grade.

4. else Clause

What is an else Clause?

The else clause provides a fallback block of code if no conditions are true.

Syntax

if condition

  code

else

  code

end

Detailed Explanation

  • Executes only if all preceding conditions evaluate to false.
  • Ensures that one block of code always runs.
  • Often paired with if or elsif for handling edge cases.

Example

age = 20

if age < 18

  puts “Underage”

else

  puts “Adult”

end

Example Explanation

  • Outputs “Adult” if age is greater than or equal to 18.

5. case Statement

What is a case Statement?

The case statement matches a variable against multiple values.

Syntax

case variable

when value

  code

else

  code

end

Detailed Explanation

  • The case statement compares a variable to a series of when conditions.
  • Executes the block of code corresponding to the first matching condition.
  • Falls back to the else block if no conditions match.
  • Supports ranges and regular expressions for advanced matching.

Example

day = “Monday”

case day

when “Monday”

  puts “Start of the work week.”

when “Friday”

  puts “End of the work week.”

else

  puts “Midweek.”

end

Example Explanation

  • Outputs “Start of the work week.” for day equal to “Monday”.

6. Ternary Operator

What is a Ternary Operator?

The ternary operator provides a shorthand for simple if-else conditions.

Syntax

condition ? true_code : false_code

Detailed Explanation

  • Evaluates the condition and executes one of two expressions based on its truth value.
  • Ideal for concise conditional assignments.
  • Not suitable for complex logic; use if-else for clarity.

Example

age = 20

puts age >= 18 ? “Adult” : “Underage”

Example Explanation

  • Outputs “Adult” if age is greater than or equal to 18.
  • Otherwise, outputs “Underage”.

Real-Life Project

Project Name: Task Prioritizer

Project Goal

Create a program to prioritize tasks based on their urgency and importance.

Code for This Project

def prioritize_task(urgency, importance)

  if urgency == "high" && importance == "high"

    "Do it now."

  elsif urgency == "low" && importance == "high"

    "Schedule it."

  elsif urgency == "high" && importance == "low"

    "Delegate it."

  else

    "Ignore it."

  end

end

puts prioritize_task("high", "high")

puts prioritize_task("low", "high")

puts prioritize_task("high", "low")

puts prioritize_task("low", "low")

Steps

  1. Define task urgency and importance as input.
  2. Use conditional statements to evaluate combinations of urgency and importance.
  3. Return a priority recommendation for each combination.

Expected Output

Do it now.

Schedule it.

Delegate it.

Ignore it.

Project Explanation

  • Demonstrates the use of multiple conditions to evaluate task priorities.
  • Highlights the versatility of conditional statements in decision-making.

Insights

Ruby’s conditional statements are essential for implementing dynamic and flexible logic. Understanding their syntax and behavior enables clean and effective code.

Key Takeaways

  • Use if-elsif-else for sequential condition checks.
  • Leverage case for multi-value comparisons.
  • Write clear and concise conditions for better readability.
  • Test edge cases to ensure robust conditional logic.