DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Enumerable#select_with_index

03.30.2007
| 6437 views |
  • submit to reddit
        


module Enumerable

   def select_with_index
      index = -1
      (block_given? && self.class == Range || self.class == Array)  ?  select { |x| index += 1; yield(x, index) }  :  self
   end

   def select_with_index_blk(&block)
      index = -1
      (block && self.class == Range || self.class == Array)  ?  select { |x| index += 1; block.call(x, index) }  :  self
   end

end


p ('a'..'n').select_with_index { |x, i| x if i % 2 == 0 }
p ('a'..'n').select_with_index_blk { |x, i| x if i % 2 == 0 }


require 'benchmark' 

num = 1000000

Benchmark.bm(8) do |t| 

  t.report('yield:') do 
    (0..num).select_with_index { |x, i| x } 
    #(0..num).select_with_index { |x, i| x if i % 2 == 0 } 
 end 

 t.report('block:') do
    (0..num).select_with_index_blk { |x, i| x } 
    #(0..num).select_with_index_blk { |x, i| x if i % 2 == 0 } 
 end 

end