Ruby Makes It Easy
Oh ruby, you make my job so simple. I need a class method you’re lacking, and you just let me add it to you.
class Array
def map_with_index(procedure=null)
result = []
if block_given?
each_with_index {|item, i| result[i] = yield(item, i) }
elsif procedure
each_with_index {|item, i| result[i] = procedure.call(item, i) }
else
result = self
end
return result
end
alias :collect_with_index :map_with_index
end
[1, 2, 3, 4].map_with_index {|elem, i| elem + i } => [1, 3, 5, 7]
See how easy that was?