not_class.rb
edited
1class Object
2 def not
3 NotClass.new(self)
4 end
5end
6
7class NotClass < BasicObject
8 instance_methods.grep(/^[^_]/).each { |m| undef_method m }
9
10 def initialize(object)
11 @object = object
12 end
13
14 def method_missing(name, *args, &block)
15 !@object.send(name, *args, &block)
16 end
17end
18
19puts nil.not.nil?
20puts 1.not.eql?(2)
21puts [1, 3, 5, 7, 9].not.any? { |i| i % 2 == 0 }
22
23require "benchmark"
24
25Benchmark.bm do |x|
26 x.report { 1.upto(1_000_000) { 1.not == 2 } }
27 x.report { 1.upto(1_000_000) { 1 != 2 } }
28end
29
30# user system total real
31# 0.302335 0.001475 0.303810 ( 0.303833)
32# 0.035334 0.000051 0.035385 ( 0.035446)