A simple method that I'm finding I use a fair amount these days is map_with_index. It works the same way as each_with_index except with the behaviour of map, ie every element of the resulting array is what's returned by the block when the element is yielded to it.

module BarkingIguana
  module ArrayExt
    def map_with_index &block
      index = 0
      map do |element|
        result = yield element, index
        index += 1
        result
      end
    end
  end
end

Array.class_eval do
  include BarkingIguana::ArrayExt
end

Great for situations where eg the first N elements of an array have to be slightly different from the rest of the elements:

[1, 2, 3, 4, 5].map_with_index do |element, index|
  model = Model.new element
  model.unlock if index < 3
end
written by
Craig
published
2011-04-01
Disagree? Found a typo? Got a question?
If you'd like to have a conversation about this post, email craig@barkingiguana.com. I don't bite.
You can verify that I've written this post by following the verification instructions:
curl -LO http://barkingiguana.com/2011/04/01/working-with-ruby-arrays-map-with-index.html.orig
curl -LO http://barkingiguana.com/2011/04/01/working-with-ruby-arrays-map-with-index.html.orig.asc
gpg --verify working-with-ruby-arrays-map-with-index.html.orig{.asc,}