Menu
Coddy logo textTech

Each with Index

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

Sometimes you need to know not just the element you're working with, but also its position in the array. Ruby's each_with_index method gives you both the element and its index in a single iteration.

Here's how it works:

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

fruits.each_with_index do |fruit, index|
  puts "#{index}: #{fruit}"
end

This outputs:

0: apple
1: banana
2: cherry

Notice that the block now takes two variables between the pipes: the element comes first, followed by the index. The index starts at 0, just like when accessing array elements directly.

This is particularly useful when you need to display numbered lists or track positions:

tasks = ["Buy groceries", "Clean room", "Call mom"]

tasks.each_with_index do |task, i|
  puts "Task #{i + 1}: #{task}"
end

By adding 1 to the index, we create a human-friendly numbered list starting from 1 instead of 0. The each_with_index method eliminates the need to manually track a counter variable, making your code cleaner and less error-prone.

challenge icon

Challenge

Easy

Read a single line of input containing comma-separated words (e.g., apple,banana,cherry,date).

Split the input into an array of strings, then use each_with_index to print each item as a numbered list starting from 1 (not 0).

Each line should follow this format: Item 1: apple

For example, if the input is apple,banana,cherry,date, the output should be:

Item 1: apple
Item 2: banana
Item 3: cherry
Item 4: date

If the input is red,green,blue, the output should be:

Item 1: red
Item 2: green
Item 3: blue

If the input is monday,tuesday,wednesday,thursday,friday, the output should be:

Item 1: monday
Item 2: tuesday
Item 3: wednesday
Item 4: thursday
Item 5: friday

If the input is solo, the output should be:

Item 1: solo

Cheat sheet

The each_with_index method allows you to iterate over an array while accessing both the element and its index:

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

fruits.each_with_index do |fruit, index|
  puts "#{index}: #{fruit}"
end

Output:

0: apple
1: banana
2: cherry

The block takes two variables: the element first, then the index. The index starts at 0.

To create human-friendly numbered lists starting from 1, add 1 to the index:

tasks = ["Buy groceries", "Clean room", "Call mom"]

tasks.each_with_index do |task, i|
  puts "Task #{i + 1}: #{task}"
end

Try it yourself

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

# Split the input into an array
items = input.split(",")

# TODO: Use each_with_index to print each item as a numbered list
# Remember: the index starts at 0, but you need to display starting from 1
# Format: "Item 1: apple"
quiz iconTest yourself

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

All lessons in Fundamentals