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]]






Advertisements

About sandipransing

Web Developer #ruby #rails #JS
This entry was posted in Ruby and tagged , , . Bookmark the permalink.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s