Conditional Looping and Control

Topic Overview

Welcome back! In this unit, we're diving into Ruby's Conditional Looping and the powerful tools provided by the break and next statements.

Loops execute code multiple times, and with conditional controls, they become even more flexible and efficient. Let's explore how these concepts work together to give us fine-grained control over our loops. We’ll also look at an alternative and more concise way of handling conditions directly in Ruby loops.

The 'if' Statement

Ruby's if statement allows our code to make decisions based on conditions. Here's a simple example where the if statement determines what message to print based on the value of temperature:

temperature = 15
if temperature > 20
  puts "Wear light clothes." # This will print if temperature is over 20.
else
  puts "Bring a jacket." # This will print otherwise.
end

In this snippet, Ruby checks the condition (temperature > 20). If it evaluates to true, it executes the corresponding block. Otherwise, the else block runs.

For more complex scenarios, you can use elsif to add additional conditions. Here's an example:

temperature = 15

if temperature > 30
  puts "It's hot outside!" # Prints if temperature is over 30.
elsif temperature > 20
  puts "The weather is nice." # Prints if temperature is between 21 and 30.
else
  puts "It might be cold outside." # Prints if temperature is 20 or below.
end

This approach allows us to evaluate multiple conditions sequentially until one matches.

Ruby also provides a more concise way to handle conditions directly in loops using break if and next if. These can sometimes make your code more readable by reducing nesting. Let’s explore how these work.

The 'break' Statement

The break statement is used to exit a loop as soon as a specified condition is met. Let’s see how this works with an example:

numbers = [1, 3, 7, 9, 12, 15]

numbers.each do |number|
  if number.even?
    puts "The first even number is: #{number}" # Prints the first even number.
    break # Exits the loop after finding the first even number.
  end
  puts "Number: #{number}"
end
# Output:
# Number: 1
# Number: 3
# Number: 7
# Number: 9
# The first even number is: 12

You can simplify this by incorporating the condition directly into the break statement:

numbers = [1, 3, 7, 9, 12, 15]

numbers.each do |number|
  break puts "The first even number is: #{number}" if number.even?
  puts "Number: #{number}"
end
# Output:
# Number: 1
# Number: 3
# Number: 7
# Number: 9
# The first even number is: 12

This approach eliminates the need for an explicit if block and makes the code more concise.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal