Sat11Sep

  1. Array#map_with_index

    Further on from my colleague Craig Webster’s post. I saw that a lot of people have wanted Array#map_with_index over the years. I found the existing implementations to be unnecessarily complex. Ruby allows something much simpler.

    class Array
      def map_with_index &blk
        enum_with_index.map &blk
      end
      alias :collect_with_index :map_with_index
    end
    
    %w(one two three).map_with_index do |item, index| 
      [item, index]
    end
    

    If you happen to be one of the cool kids on 1.9 the solution if even more delicious and expressive.

    %w(one two three).map.with_index do |item, index| 
      [item, index]
    end

    This is because when one calls and method from Enumerable without supplying a block, an instance of Enumerator is returned. Nice!