CodeToLive

Control Structures in Ruby

Control structures in Ruby allow you to control the flow of your program. They include conditional statements (if-else, unless, case) and loops (for, while, until).

If-Else Statements

The if-else statement is used to execute a block of code based on a condition.


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

Ternary Operator

The ternary operator is a concise way to write simple if-else statements.


age = 20
puts age >= 18 ? "You are an adult." : "You are a minor."
      

Unless Statement

The unless statement is the opposite of if. It executes code when the condition is false.


age = 15
unless age >= 18
    puts "You are a minor."
else
    puts "You are an adult."
end
      

Case Statement

The case statement is used to compare a value against multiple patterns.


grade = 'B'
case grade
when 'A'
    puts "Excellent!"
when 'B'
    puts "Good job!"
when 'C'
    puts "You can do better."
else
    puts "Invalid grade."
end
      

Loops

Loops are used to execute a block of code repeatedly. Ruby supports for, while, and until loops.


# For Loop
for i in 0..4
    puts i
end

# While Loop
count = 0
while count < 5
    puts count
    count += 1
end

# Until Loop
count = 0
until count == 5
    puts count
    count += 1
end
      

Break and Next in Loops

Use break to exit a loop and next to skip to the next iteration.


# Break Example
count = 0
while true
    puts count
    count += 1
    break if count == 5
end

# Next Example
for i in 0..4
    next if i == 2
    puts i
end
      

Nested Loops

Loops can be nested inside other loops to handle more complex scenarios.


# Nested Loop Example
for i in 1..3
    for j in 1..3
        puts "i: #{i}, j: #{j}"
    end
end
      

Iterators

Ruby also provides iterators like each, map, and select for collections.


# Each Iterator
[1, 2, 3, 4, 5].each do |num|
    puts num
end

# Map Iterator
squared_numbers = [1, 2, 3, 4, 5].map { |num| num ** 2 }
puts squared_numbers.inspect

# Select Iterator
even_numbers = [1, 2, 3, 4, 5].select { |num| num.even? }
puts even_numbers.inspect
      

Interactive Code Examples

Try running these examples in your Ruby environment to see how they work!


# Interactive Example
puts "Enter a number:"
num = gets.chomp.to_i
if num > 0
    puts "Positive number."
elsif num < 0
    puts "Negative number."
else
    puts "Zero."
end
      

Practice Problems

Test your understanding with these practice problems:

  1. Write a Ruby program to check if a number is even or odd.
  2. Write a Ruby program to print the first 10 natural numbers using a while loop.
  3. Write a Ruby program to find the sum of all elements in an array using the each iterator.
Next: Functions