From: Stefano Crocco Date: 2010-12-26T17:59:38+09:00 Subject: Re: array index inside map function On Sunday 26 December 2010 17:47:19 Peter Vandenabeele wrote: > Siddharth Venkatesan wrote in post #970728: > > Hi all, > > > > how can i access the index of the element inside the map argument block? > > > > "101010,234,876".split(",").map {|c| get_something(c)} > > > > this works. But the problem is i need to apply the get_something on only > > the > > second and third element of the array. How can I check the index of the > > element inside the map block? > > There is each_with_index, but that has the "each" functionality > and not the "map"/"collect" functionality. > > That would be (not tested): > result = [] > "101010,234,876".split(",").each_with_index {|c, i| result << > do_something(c,i)} > > HTH, > > Peter If you're using ruby 1.8.7 or later, calling each_with_index without a block returns an enumerator, so that you can write something like: "101010,234,876".split(",").each_with_index.map do |c, i| i == 1 or i == 2 ? get_something(c) : c end I hope this helps Stefano