Menu
Coddy logo textTech

Each Iterator

Part of the Fundamentals section of Coddy's Ruby journey — lesson 65 of 88.

Ruby provides a more elegant way to loop through arrays than using for or while loops. The each iterator is the preferred Ruby way to process every element in a collection.

Here's the basic syntax:

fruits = ["apple", "banana", "cherry"]

fruits.each do |fruit|
  puts fruit
end

This outputs each fruit on a separate line. The variable between the pipes (|fruit|) is called a block variable. It temporarily holds each element as the iterator moves through the array.

For single-line blocks, you can use curly braces instead of do...end:

numbers = [1, 2, 3]
numbers.each { |n| puts n * 2 }

The each method is powerful because you can perform any operation on each element. Here's an example that calculates a running total:

prices = [10, 25, 15]
total = 0

prices.each do |price|
  total += price
end

puts total  # Outputs: 50

Unlike for loops, the block variable in each stays contained within the block, keeping your code cleaner and less prone to unexpected behavior.

challenge icon

Challenge

Easy

Read a single line of input containing comma-separated integers (e.g., 4,7,2,9,5).

Split the input into an array of integers, then use the each iterator to:

  1. Print each number multiplied by 3 on its own line
  2. Calculate the sum of all numbers and print it after the loop

Use a variable initialized to 0 before the loop to accumulate the sum as you iterate through the array.

For example, if the input is 4,7,2,9,5, the output should be:

12
21
6
27
15
Sum: 27

If the input is 10,20,30, the output should be:

30
60
90
Sum: 60

If the input is 1,2,3,4, the output should be:

3
6
9
12
Sum: 10

If the input is 5, the output should be:

15
Sum: 5

Cheat sheet

The each iterator is the preferred Ruby way to loop through arrays:

fruits = ["apple", "banana", "cherry"]

fruits.each do |fruit|
  puts fruit
end

The variable between pipes (|fruit|) is a block variable that temporarily holds each element.

For single-line blocks, use curly braces:

numbers = [1, 2, 3]
numbers.each { |n| puts n * 2 }

You can perform operations on each element, such as calculating a running total:

prices = [10, 25, 15]
total = 0

prices.each do |price|
  total += price
end

puts total  # Outputs: 50

Try it yourself

# Read the comma-separated integers
input = gets.chomp

# Split the input into an array of integers
numbers = input.split(",").map(&:to_i)

# Initialize sum variable
sum = 0

# TODO: Write your code below
# Use the each iterator to:
# 1. Print each number multiplied by 3
# 2. Add each number to the sum variable

# Print the final sum
puts "Sum: #{sum}"
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals