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}"
endThis outputs:
0: apple
1: banana
2: cherryNotice 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}"
endBy 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
EasyRead 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: dateIf the input is red,green,blue, the output should be:
Item 1: red
Item 2: green
Item 3: blueIf 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: fridayIf the input is solo, the output should be:
Item 1: soloCheat 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}"
endOutput:
0: apple
1: banana
2: cherryThe 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}"
endTry 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"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