Never been to DZone Snippets before?

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

About this user

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Enumerable#select_with_index



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 


« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS