Extend enumerable functionality to iterate along with index
module Enumerable
def collect_with_index(i=0)
collect{|elm| yield(elm, i+=1)}
end
alias map_with_index collect_with_index
end
Example use :
ree-1.8.7-2010.01 > ['ruby', 'rails', 'sandip'].map_with_index{ |w,i| [w, i] }
#=> [["ruby", 1], ["rails", 2], ["sandip", 3]]
ree-1.8.7-2010.01 > ['ruby', 'rails', 'sandip'].collect_with_index{ |w,i| [w, i] }
#=> [["ruby", 1], ["rails", 2], ["sandip", 3]]
#By default index starts from zero to specify custom index to start from,
#pass index to collect_with_index
ree-1.8.7-2010.01 > ['ruby', 'rails', 'sandip'].map_with_index(-1){ |w,i| [w, i] }
#=> [["ruby", 0], ["rails", 1], ["sandip", 2]]
ree-1.8.7-2010.01 > ['ruby', 'rails', 'sandip'].map_with_index(5){ |w,i| [w, i] }
#=> [["ruby", 6], ["rails", 7], ["sandip", 8]]