Ruby: Change the start value of Array index

Chris Houghton
2 min readApr 6, 2022

Working on a project the other day I came across an issue where I needed to add a different value to the staring index of an Array. Normally arrays start at the value of 0. I needed the value to start at 1 and typically when working with array elements that require the index I would use

arr = ['a','b','c']arr.each_with_index do |element, index| 
puts index
end
//output:
0
1
2

The solution to this problem is almost the same line of code albeit small differences

arr = ['a','b','c']arr.each.with_index(1) do |element, index| 
puts index
end
//output:
1
2
3

The solution lies in the chained form of with_index which takes an argument for the starting index value of the first element. Here I used this solely to change the output value of the array’s index positions.

Something to note, each_with_index runs slightly faster than .with_index() which from my experience so far is typically the case with method chaining. A single method usually runs faster than a chain which seems to be why these methods exist in my opinion.

Extra: when using the index of one array to manipulate another I found the index value is actually changed inside the block. I this example we changed the start index value to 2 and output the elements starting at 2 in the new array.

arr = ['a','b','c']newArr = ["q", "w", "e", "r", "t", "y"]arr.each.with_index(2) do |elem, ind|
puts newArr[ind]
end
//output:
e
r
t

--

--