Scott Watermasysk
Ruby Map With Index
Ruby has a built-in helper on Enumerable called - each_with_index
# An array of fruits
fruits = ["Apple", "Banana", "Cherry", "Date"]
# Using each_with_index to print each fruit with its index
fruits.each_with_index do |fruit, index|
puts "#{index}: #{fruit}"
end
Unfortunately, there is no equivalent for the Enumerable#map.
['a','b'].map_with_index {|item,index|} # => undefined method
map_with_index'`
There are easy ways to work around this, but the cleanest is by chaining with_index
to .map
fruits = ["Apple", "Banana", "Cherry", "Date"]
result = fruits.map.with_index do |fruit, index|
"#{index}: #{fruit}" # Format the output with index
end
Why? My guess is to keep the number of methods smaller over time. Technically each_with_index could be deprecated since Enumerable#each.with_index is available. This way, we do not need a _with_index for everything on Enermable.
(1..100)
.select
.with_index {|n, index| (n % 2 == 0) && (index % 5 == 0)}
# [6, 16, 26, 36, 46, 56, 66, 76, 86, 96]