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
endThis 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: 50Unlike for loops, the block variable in each stays contained within the block, keeping your code cleaner and less prone to unexpected behavior.
Challenge
EasyRead 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:
- Print each number multiplied by 3 on its own line
- 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: 27If the input is 10,20,30, the output should be:
30
60
90
Sum: 60If the input is 1,2,3,4, the output should be:
3
6
9
12
Sum: 10If the input is 5, the output should be:
15
Sum: 5Cheat sheet
The each iterator is the preferred Ruby way to loop through arrays:
fruits = ["apple", "banana", "cherry"]
fruits.each do |fruit|
puts fruit
endThe 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: 50Try 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}"This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 42Variables and Data Types
Numbers and VariablesString Data TypeBoolean Data TypeSymbol Data TypeChecking Data TypesNaming ConventionsRecap - Variable Creation8Loops
For Loop with RangesWhile LoopBreakNextRecap - FactorialTimes LoopUntil LoopNested LoopsRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators6Basic IO
Output with putsOutput with print and pOutput With VariablesInput with getsChomp MethodType ConversionRecap - Age CalculatorRecap - True or False