Skip to content

Instantly share code, notes, and snippets.

@Mikoangelo
Forked from reinh/comprehend.rb
Created March 10, 2009 19:57
Show Gist options
  • Save Mikoangelo/77102 to your computer and use it in GitHub Desktop.
Save Mikoangelo/77102 to your computer and use it in GitHub Desktop.
Now featuring results
module Enumerable
def comprehend(&block)
map(&block).compact
end
def comprehend2(&block)
inject([]){|arr, x| result = block[x]; arr << result if result; arr}
end
def comprehend3(&block)
arr = []
each do |x|
result = block[x]
arr << result if result
end
arr
end
def comprehend4(&block)
map(&block).reject{|x| x.nil?}
end
end
require "benchmark"
block = lambda {|x| x * 2 if x > 50 }
arr = (1..100_000).to_a
TESTS = 10
Benchmark.bmbm do |results|
results.report("map, compact") {TESTS.times{arr.comprehend(&block)}}
results.report("inject") {TESTS.times{arr.comprehend2(&block)}}
results.report("accumulator") {TESTS.times{arr.comprehend3(&block)}}
results.report("map, reject") {TESTS.times{arr.comprehend4(&block)}}
end
Rehearsal ------------------------------------------------
map, compact 1.090000 0.040000 1.130000 ( 2.573331)
inject 19.150000 0.370000 19.520000 ( 34.193527)
accumulator 11.760000 0.220000 11.980000 ( 16.703419)
map, reject 1.740000 0.040000 1.780000 ( 2.365760)
-------------------------------------- total: 34.410000sec
user system total real
map, compact 1.080000 0.030000 1.110000 ( 1.440510)
inject 12.800000 0.230000 13.030000 ( 17.273436)
accumulator 6.270000 0.120000 6.390000 ( 8.737844)
map, reject 1.640000 0.050000 1.690000 ( 2.296689)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment