/ Published in: Ruby
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
require 'benchmark' # The original implementation by Daniel DeLorme # http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/256662 class NilClass def ergo @blackhole ||= Object.new.instance_eval do class << self for m in public_instance_methods undef_method(m.to_sym) unless m =~ /^__.*__$/ end end def method_missing(*args); nil; end self end @blackhole unless block_given? end end class Object def ergo if block_given? yield(self) else self end end end a,b = [1,2,3], nil n = 100_000 Benchmark.bm(15) do |x| x.report("Original") do n.times { a.ergo[0]; b.ergo[0] } end # Turn to facets implementation require 'rubygems' require 'facets/nilclass/ergo' x.report("Facets") do n.times { a.ergo[0]; b.ergo[0] } end x.report("Logic operators") do n.times { a && a[0]; b && b[0] } end end