From: Stefan Lang Date: 2008-03-05T21:05:54+09:00 Subject: Re: collect with index? 2008/3/5, Tim Conner : > simple question: how can I do a collect with index? This should be > like each_with_index but should return a new array containing the values > returned by the block. > i.e > Say i want to return: > ["cat number 1","dog number 2","pig number 3" > > how would i do this? I am thinking that there must be something along > the lines of: > %w{"cat","dog","pig"}.collect_with_index {|animal,index| animal+" number > "+index} >> require "enumerator" => true >> ary = ["cat", "dog", "pig"] => ["cat", "dog", "pig"] >> ary.enum_for(:each_with_index).collect { |animal, index| "#{animal} number #{index + 1}" } => ["cat number 1", "dog number 2", "pig number 3"] Or in Ruby 1.9 it's simply: >> ary = ["cat", "dog", "pig"] => ["cat", "dog", "pig"] >> ary.each_with_index.collect { |animal, index| "#{animal} number #{index + 1}" } => ["cat number 1", "dog number 2", "pig number 3"] HTH, Stefan