Sha256: 4065e7d05fea4272a35f49753bb51ad414d79892cd0bb30e6f4a483c4ec625db
Contents?: true
Size: 1.48 KB
Versions: 1
Compression:
Stored size: 1.48 KB
Contents
=begin rdoc = NilComparable NilComparable does two things. First it make nil comparable, such that all things (except itself) are greater than it. Secondly it provides a module called NilComparable to include into any other class to allow it to compare itself to NilClass as the greater of the two. = Author(s) * Paul Brannan * Thomas Sawyer =end class NilClass include Comparable def <=>(x) x.nil? ? 0 : -1 end alias_method( :cmp, :<=> ) end # # Calling this method for a given class allows instances # # of a class to be compared to nil using <=>. # # Adapted from code by Paul Brannan (Ruby License) # # NOTE: THIS SHOULD BE A CLASS INCLUDING MODULE, I THINK. # def nil_comparable(klass=self) # klass.class_eval %{ # if method_defined?( :<=> ) # alias_method :compare_without_nil, :<=> # else # def compare_without_nil( other ) # raise TypeError, "Cannot compare \#{self.inspect} to \#{other.inspect}" # end # end # def <=>( other ) # return 1 if other.nil? # compare_without_nil( other ) # end # } # end module NilComparable def self.included( mod ) mod.class_eval %{ if method_defined?( :<=> ) alias_method :compare_without_nil, :<=> else def compare_without_nil( other ) raise TypeError, "Cannot compare \#{self.inspect} to \#{other.inspect}" end end def <=>( other ) return 1 if other.nil? compare_without_nil( other ) end } end end
Version data entries
1 entries across 1 versions & 1 rubygems
Version | Path |
---|---|
carats-0.3.0 | lib/carat/nil-comparable.rb |