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-2 of 2 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 


List Comprehensions in Ruby

Taken from: http://www.ruby-forum.com/topic/89416
Author: Phrogz

To avoid reinventing the wheel check out the built-in methods described in:
http://www.ruby-doc.org/core/classes/Array.html and
http://www.ruby-doc.org/core/classes/Enumerable.html.



#class Array 
module Enumerable
  def comprehend(&block) 
    block ? map(&block).compact : self 
  end 
end 


old_data = *(1..5)          # alternatives to the splat operator: (1..5).to_a or (1..5).collect
new_data = *(3..9)


# some reinventing going on here ...
added = new_data.comprehend { |x| x if not old_data.include?(x) } 
removed = old_data.comprehend { |x| x if not new_data.include?(x) } 
same = new_data.comprehend { |x| x if old_data.include?(x) } 
modified = new_data.comprehend { |x| x**2 if not x % 2 == 0 }

p added                                            #=> [6, 7, 8, 9]
p added = new_data - old_data                      #=> [6, 7, 8, 9]

p removed                                         #=> [1, 2]
p removed = old_data - new_data                   #=> [1, 2]

p same                                              #=> [3, 4, 5]
p same = old_data & new_data                        #=> [3, 4, 5]
 
p modified                                        #=> [9, 25, 49, 81]


new_data = [[5, 9], [22, 3], [99, 564]]
bool_vals = new_data.comprehend { |x, y| x <= y }
p bool_vals                                      #=> [true, false, true]


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