Class: Object

Inherits:
BasicObject
Defined in:
lib/range_extd/infinity/infinity.rb

Overview

class Object

Overwrite #<=>() so all its sub-classes can be aware of RangeExtd::Infinity objects (the two constants).

Instance Method Summary collapse

Instance Method Details

#<=>(c) ⇒ Object

Overwrite #<=>(). Then, all its sub-classes can be aware of RangeExtd::Infinity objects (the two constants).

In this definition of #<=>, if self is Comparable (by judging whether it has the method [#<=]), it always returns, unless infinity? and positive? are set accordingly, either -1 or 1, depending which of

RangeExtd::Infinity::(NEGATIVE|POSITIVE)

is compared. If self is not Comparable, the original [#<=>] is called, which should return nil (unless both the object_id agree, eg., nil and nil, in which case 0 is returned).

If you define your own class, which is Comparable, you should define the method “<=>” as follows, as in the standard practice when you redefine a method that exists in a superclass;

Examples:

A method definition of user-defined Comparable class

class MyComparableClass 
  include Comparable
  # alias :cmp_orig :<=> if !self.method_defined?(:cmp_orig)  # if you want
  def <=>(c)
    if c._is_what_i_expect?
      # Write your definition.
    else       # When self does not know what to do with c.
      super    # to call Object#<=>
    end
  end
end


358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
# File 'lib/range_extd/infinity/infinity.rb', line 358

def <=>(c)
  if defined?(self.<=) && RangeExtd::Infinity === c
    # if defined?(self.<=) && defined?(c.infinity?) && defined?(c.positive?)
    # NOTE: Duck-typing is inappropriate here.
    #   Only the objects that self wants to deal with here are
    #   the instances of RangeExtd::Infinity, and not other
    #   "infinity" object, such as, Float::INFINITY.  So,
    #     (self <=> RangeExtd::Infinity::POSITIVE)  # => -1
    #     (self <=> Float::INFINITY)                # => nil
    #   in default.
    if defined?(self.infinity?) && defined?(self.positive?)
      if (self.positive? ^! c.positive?)
        0
      elsif self.positive?
        1
      else
        -1
      end
    else
      # (c <=> self) * (-1)
      if c.positive?
        -1
      else
        1
      end
    end
  elsif object_id == c.object_id  # (nil <=> nil)  # => 0
    0
  else
    nil
  end # if defined?(self.<=) && RangeExtd::Infinity === c
end

#compare_obj_before_infinityObject

No overwriting.



327
# File 'lib/range_extd/infinity/infinity.rb', line 327

alias_method :compare_obj_before_infinity, :<=>