An approach that might work for you is to override the #nil method? in the null object. Does this mean that in your code you must use obj.nil to check for a null value? and not just check the existence of obj. This is probably reasonable since you can distinguish between nil and null. The following is an example:
class NullClass def nil? true end def null_behavior puts "Hello from null land" end end
Inheritance will work:
class NewClass < NullClass end
Use like this:
normal = Class.new null = NewClass.new x = [normal, null] x.each do |obj| if obj.nil? puts "obj is nil" obj.null_behavior end end
Output:
obj is nil Hello from null land
Remember to use # .nil? for any checks that require Null and Nil to be false.
Below this line was my INCORRECT initial answer
CustomNil = Class.new(NilClass) class CustomNil def self.new ###!!! This returns regular nil, not anything special. end end
[tests removed for brevity]
Use at your own risk. I have not investigated what side effects this can cause or will do what you want. But it looks like it really has something like nil like
source share