NilComparable
This microframework simply makes nil comparable, such that all things (except itself) are greater than it.
Usage
The main effect is this.
nil <=> any_object #=> -1
To enable a class to compare against nil (reverse of the above), simply prepend a nil comparsion into the #<=> method of that class. For example:
class Foo def initialize( value ) @value = value end def <=>( other ) return 1 if other.nil? # nil comparison @value <=> other end end
To do so for a pre-existing class with a pre-existing #<=> method, you’ll need to overide the method. As an example let’s make Numeric comparable to nil.
class Numeric alias_method :compare_without_nil, :<=> def <=>( other ) return 1 if other.nil? compare_without_nil( other ) end end
Or more conveniently:
require 'facet/module/wrap_method' Numeric.wrap_method(:<=>) do |prev, other| return 1 if other.nil? prev.call( other ) end
Note
NilCompariable was a module that could automatically make a class comparable to nil. But it only worked if the #<=> was previous defined, which isn’t ideal. Since it is easy enough to use the above examples, we decided to deprecate the module and leave this as an explicit task for the end-programmer. Changing this behavior for built-in classes is not something to be done lightly anyway.
- Comparable
[ show source ]
# File lib/facets/more/nilcomparable.rb, line 91 def <=>(x) x.nil? ? 0 : -1 end
[ show source ]
# File lib/facets/more/nilcomparable.rb, line 97 def succ; nil; end
Returns a JSON string for nil: ‘null’.
[ show source ]
# File lib/facets/more/json.rb, line 638 def to_json(*) 'null' end