Extend enumerable to add method collect_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]]






Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.