Ruby example

How to loop with an index in Ruby

8 min read Updated Dec 2026 Runs in an isolated runtime
Quick answer

Use each_with_index: fruits.each_with_index { |fruit, i| puts "#{i}: #{fruit}" }. The element comes first and the index second. To count from 1, write each.with_index(1), and to build a new array from elements and indexes, use map.with_index { |x, i| … }.

Ruby loops are method calls with a block: each walks an array, and each_with_index hands the block the position as well, so you rarely write a counter yourself. The sections below cover each_with_index and with_index(1), transforming with map.with_index, plain counting with times, upto and downto, stepping through a range in increments, turning a range into an array, and why Ruby code uses each instead of for, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.

1each_with_index and with_index(1)Recommended

each_with_index calls the block once per element with two arguments: the element, then its index, starting at 0. Python readers: the order is the reverse of for i, x in enumerate(items). To start at 1 (or any number), chain with_index(1) onto each; each_with_index itself takes no offset. On a hash, each element is a [key, value] pair, so unpack it with parentheses in the block parameters.

each_with_index.rb
fruits = ["apple", "banana", "cherry"]

# each_with_index yields the element first, then its index
fruits.each_with_index do |fruit, i|
  puts "#{i}: #{fruit}"
end

# Start counting at 1 with each.with_index(1)
fruits.each.with_index(1) do |fruit, n|
  puts "#{n}. #{fruit}"
end

# A hash yields [key, value] pairs: unpack them with parentheses
prices = { apple: 1.2, banana: 0.5 }
prices.each_with_index do |(name, price), i|
  puts "#{i} #{name} costs #{price}"
end

# The return value is the receiver, not what the block returned
result = fruits.each_with_index { |fruit, i| fruit.upcase }
p result

Output

The first loop prints 0: apple to 2: cherry; the second numbers the same fruits 1. to 3.. The hash loop gets name, price and the index from |(name, price), i|; without the parentheses, name would hold the whole pair. The last line shows that each_with_index returns the original array, ["apple", "banana", "cherry"], and throws the block's upcase results away: loops are for side effects, and the next section collects results. To skip an element or stop early, see how to skip to the next iteration.

2Transform with the index: map.with_index

There is no map_with_index method. Called without a block, map returns an enumerator, and with_index on that enumerator adds the index, so map.with_index collects the block's results with the position available. The same trick works for select, reject and filter_map, and with_index(1) takes an offset here too. each_with_index.map gives the same result as map.with_index. To build a hash, add with_object, or call to_h on the pairs.

map_with_index.rb
names = ["ann", "bob", "cy"]

# map.with_index: transform each element using its index
p names.map.with_index { |name, i| "#{i}:#{name}" }

# with_index takes a starting offset
p names.map.with_index(1) { |name, n| "#{n}. #{name.capitalize}" }

# each_with_index.map gives the same kind of result
p names.each_with_index.map { |name, i| [i, name] }

# Keep the elements at even indexes
p names.select.with_index { |_, i| i.even? }

# filter_map: keep and transform in one pass
p names.filter_map.with_index { |name, i| name.upcase if i > 0 }

# Build a hash of name => position
p names.each_with_index.to_h
p names.each.with_index(1).with_object({}) { |(name, n), h| h[n] = name }

# Without a block you get an enumerator of [element, index] pairs
p names.each_with_index.to_a

Output

map.with_index returns the new array ["0:ann", "1:bob", "2:cy"], and the offset version numbers from 1. select.with_index keeps ["ann", "cy"], the elements at indexes 0 and 2; the _ marks the element as unused. filter_map drops the nil the block returns for index 0, so only ["BOB", "CY"] is left. With with_object the block gets |(name, n), h|: the element and index as one pair, then the object being built, and the whole call returns that hash. The last line shows what these chains are made of: an enumerator of [element, index] pairs.

3Counting loops: times, upto, downto and each_index

When you need a number rather than an element, ask an integer to count: n.times runs a block n times with 0 to n - 1, and upto and downto count between two numbers, including both. A range with each does the same: 0...n leaves the end out like Python's range(n), while 0..n includes it. For an array's indexes only, use each_index; to walk two arrays side by side, zip pairs them without any index at all.

counting_loops.rb
# n.times runs the block n times, counting from 0
3.times { |i| puts "Attempt #{i + 1} (i = #{i})" }

# upto and downto include both ends
1.upto(3) { |n| puts "Chapter #{n}" }
3.downto(1) { |n| puts "#{n}..." }
puts "Liftoff"

# Without a block they return enumerators: to_a shows the values
p 4.times.to_a
p 2.upto(5).to_a

# A range: .. includes the end, ... leaves it out
(0...2).each { |i| puts "Row #{i}" }

# Only the indexes of an array
colors = ["red", "green", "blue"]
sizes = ["S", "M", "L"]
colors.each_index { |i| puts "#{colors[i]}-#{sizes[i]}" }

# zip pairs two arrays without any index
colors.zip(sizes) { |color, size| puts "#{color}/#{size}" }

# Backwards, keeping each element's original index
colors.each_with_index.reverse_each { |c, i| puts "#{i} #{c}" }

Output

3.times yields 0, 1 and 2, which is why the script adds 1 for the attempt number, while 1.upto(3) yields 1 to 3 and 3.downto(1) counts back to 1. 4.times.to_a is [0, 1, 2, 3], and (0...2) stops at Row 1. each_index pairs red-S to blue-L, and zip prints the same pairs with no index to get wrong. The last loop runs backwards and still reports each color's original position, from 2 blue down to 0 red.

4Steps, chunks and windows: step, each_slice, each_cons

To go through a range in increments, call step on it: (0..10).step(3) yields 0, 3, 6 and 9. Numeric#step does the same from a number, as 0.step(10, 3) or with the keywords by: and to:, and it can count down with a negative step or use floats. On a range, % is another name for step. To take every nth element of an array, test the index with %, or cut the array into groups with each_slice; each_cons gives overlapping windows, handy for comparing each element with the next.

step.rb
# Range#step: every 3rd value from 0 up to 10
(0..10).step(3) { |i| puts "i = #{i}" }

# Without a block, step returns a sequence: to_a shows it
p (0..10).step(3).to_a
p ((0..10) % 3).to_a
p 0.step(10, 3).to_a
p 1.step(by: 2, to: 9).to_a

# Numeric#step can count down and use floats
p 10.step(0, -4).to_a
p 1.0.step(2.0, 0.25).to_a

# Every 3rd element of an array, by index
letters = ("a".."h").to_a
p letters.select.with_index { |_, i| (i % 3).zero? }
p letters.each_slice(3).map(&:first)

# Chunks of 3, and sliding windows of 2
p (1..7).each_slice(3).to_a
p [1, 2, 4, 7].each_cons(2).to_a
p [1, 2, 4, 7].each_cons(2).map { |a, b| b - a }

Output

All four ways of writing "0 to 10 by 3" give [0, 3, 6, 9]: the step stops at the last value that does not pass the end, so 10 itself is not reached. 10.step(0, -4) counts down to [10, 6, 2], and a float step of 0.25 lands exactly on 2.0. Both ways of taking every third letter give ["a", "d", "g"]. each_slice(3) leaves a short last group, [7], and each_cons(2) turns [1, 2, 4, 7] into the gaps [1, 2, 3].

5Turn a range into an array

A range such as 1..5 is not an array; it only stores its two ends. Call to_a to get the values, or use the splat [*1..5], or Array(1..5); all three give the same array. When each element depends on its index, Array.new(n) { |i| … } builds the array directly, which is the Ruby version of a list built in a counting loop. Combine with step or downto for other sequences.

range_to_array.rb
# Three ways to turn a range into an array
p (1..5).to_a
p [*1..5]
p Array(1..5)

# ... leaves the end out; letters work too
p (1...5).to_a
p ("a".."e").to_a

# Array.new(n) { |i| ... } builds n elements from their index
p Array.new(5) { |i| i * i }
p Array.new(3) { |i| "item#{i + 1}" }

# With a step, or backwards
p (0..20).step(5).to_a
p 5.downto(1).to_a
p (1..5).to_a.reverse

# Array.new(n, value) shares ONE object; the block makes new ones
shared = Array.new(2, [])
shared[0] << "x"
p shared
fresh = Array.new(2) { [] }
fresh[0] << "x"
p fresh

Output

The first three lines all print [1, 2, 3, 4, 5], and Array.new(5) { |i| i * i } gives the squares [0, 1, 4, 9, 16]. A range cannot count down on its own: (5..1).to_a is empty, so use 5.downto(1) or reverse the array. The last two lines show the classic trap: Array.new(2, []) puts the same array object in both slots, so pushing into one shows up in both ([["x"], ["x"]]), while the block form creates a new array for each slot ([["x"], []]).

6Why each, not for

Ruby has a for … in loop, and coming from Python or JavaScript it looks like the natural choice, but idiomatic Ruby uses each. Under the hood for calls each, with one difference: it does not open a new scope. The loop variable and any variable assigned inside the body stay defined after the loop, and every pass reuses the same variable, which matters as soon as a block or lambda captures it. A while loop with a counter also works, but you manage the index by hand.

for_vs_each.rb
# for works, but its variable lives on after the loop
for n in [1, 2, 3]
  doubled = n * 2
end
p n
p doubled

# each gives the block its own scope
[1, 2, 3].each do |m|
  tripled = m * 3
end
p defined?(m)
p defined?(tripled)

# for reuses one variable, so closures all see the last value
from_for = []
for i in 1..3
  from_for << -> { i }
end
p from_for.map(&:call)

from_each = []
(1..3).each { |j| from_each << -> { j } }
p from_each.map(&:call)

# A manual while loop needs its own counter
k = 0
while k < 3
  print k
  k += 1
end
puts

Output

After the for loop, n is still 3 and doubled is 6; after the each loop, defined? returns nil for both m and tripled because they lived only inside the block. The lambdas show the real bug: the three created in the for loop all return [3, 3, 3], since they share one i, while the ones from each keep their own values, [1, 2, 3]. The while loop prints 012, with k left over at 3 afterwards, the same leak as for.

7Which should you use?

MethodGives the blockReturnsBest for
arr.each_with_indexElement, index from 0The arrayLooping with the position: most cases
arr.each.with_index(1)Element, index from 1The arrayNumbered lists for people
arr.map.with_indexElement, indexNew arrayTransforming with the position
n.times / upto / downtoA numberThe receiverRepeating or counting, no array
(a..b).step(n)Every nth numberThe rangeRanges in increments
arr.each_indexIndex onlyThe arrayIndex into several arrays (or use zip)
for x in arrElementThe arrayAvoid: leaks its variable, shares it in closures

Frequently asked questions

What is the Ruby version of Python's enumerate()?

each_with_index. The block gets the element first and the index second, the reverse of for i, x in enumerate(items). For enumerate(items, 1), write items.each.with_index(1) { |x, n| … }, and without a block items.each_with_index.to_a gives [element, index] pairs.

Why does each_with_index(1) raise an error?

each_with_index passes its arguments on to each, and Array#each takes none, so ["x", "y"].each_with_index(1) raises ArgumentError: wrong number of arguments (given 1, expected 0). The offset belongs to with_index: arr.each.with_index(1), or arr.map.with_index(1) when you collect results.

Is there a map_with_index in Ruby?

No. ["x", "y"].map_with_index { … } raises NoMethodError: undefined method 'map_with_index' for an instance of Array. Use map.with_index { |x, i| … } or each_with_index.map { |x, i| … }; both return a new array.

What is the Ruby version of Python's range(start, stop, step)?

A range with step: (0...10).step(3) yields 0, 3, 6 and 9. Use three dots to leave the end out as Python does; two dots include it. 0.step(9, 3) and 0.step(by: 3, to: 9) are the same thing written from the number, and .to_a turns any of them into an array.

How do I loop backwards with an index?

For the original positions, call arr.each_with_index.reverse_each { |x, i| … }, which starts at the last element and keeps each index. For a plain countdown, use (arr.size - 1).downto(0) { |i| … }. arr.reverse.each_with_index also works, but its indexes count from 0 in the reversed array.

Does each return the values from the block?

No. each and each_with_index return the array they were called on, so fruits.each_with_index { |f, i| f.upcase } gives back the original fruits. To collect what the block returns, use map (or map.with_index); to keep some elements, use select or filter_map.

Run it yourself

Open any of these in the full Ruby editor to tweak, run and share.

Ruby playground