Thursday, February 18, 2010

Extend enumerable to add method collect_with_index

by Sandip Ransing 0 comments

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

blog comments powered by Disqus

About The Author

Sandip is a ruby on rails developer based in pune and also a blogger at funonrails. Opensource contributor and working with Josh software Private Limited. for more info read Follow Sandip on Twitter for updates.

Connect With Me...

Github Projects

@sandipransing Twitter