# module Comparable

### Public Class Methods

[](*accessors) click to toggle source

Automatically generate comparitive definitions based on attribute fields.

    include Comparable[:a, :b]

is equivalent to including a module containing:

    def <=>(other)
      cmp = self.a <=> other.a; return cmp unless cmp == 0
      cmp = self.b <=> other.b; return cmp unless cmp == 0
      0
    end

    # File lib/facets/comparable/op_get.rb, line 16
    def self.[](*accessors)
      Module.new do
        include Comparable
        define_method(:comparability){ accessors }
        define_method(:<=>) do |other|
          comparability.each do |a|
            cmp = (send(a) <=> other.send(a))
            break cmp unless cmp == 0
          end
        end
      end
    end

### Public Instance Methods

at_least(lower) click to toggle source

Returns the lower of self or x.

    4.at_least(5)  #=> 5
    6.at_least(5)  #=> 6

CREDIT: Florian Gross

    # File lib/facets/comparable/cap.rb, line 10
    def at_least(lower)
      (self >= lower) ? self : lower
    end

at_most(upper) click to toggle source

Returns the greater of self or x.

    4.at_most(5)  #=> 4
    6.at_most(5)  #=> 5

CREDIT: Florian Gross

    # File lib/facets/comparable/cap.rb, line 21
    def at_most(upper)
      (self <= upper) ? self : upper
    end

Also aliased as: cap
bound(lower, upper=nil)

Returns self if above the given lower bound, or within the given lower and upper bounds, otherwise returns the the bound of which the value falls outside.

    4.bound(3)    #=> 4
    4.bound(5)    #=> 5
    4.bound(2,7)  #=> 4
    9.bound(2,7)  #=> 7
    1.bound(2,7)  #=> 2

CREDIT: Florian Gross

Alias for: clip
cap(upper)

Returns the greater of self or x.

    4.cap(5)  #=> 4
    6.cap(5)  #=> 5

CREDIT: Trans

Alias for: at_most
clip(lower, upper=nil) click to toggle source

Returns self if above the given lower bound, or within the given lower and upper bounds, otherwise returns the the bound of which the value falls outside.

    4.clip(3)    #=> 4
    4.clip(5)    #=> 5
    4.clip(2,7)  #=> 4
    9.clip(2,7)  #=> 7
    1.clip(2,7)  #=> 2

CREDIT Florian Gross, Trans

    # File lib/facets/comparable/clip.rb, line 16
    def clip(lower, upper=nil)
      return lower if self < lower
      return self unless upper
      return upper if self > upper
      return self
    end

Also aliased as: bound
cmp(o) click to toggle source

Alternate name for comparison operator #<=>.

    3.cmp(1)   #=>  1
    3.cmp(3)   #=>  0
    3.cmp(10)  #=> -1

This fundamental compare method is used to keep comparison compatible with `#succ`.

CREDIT: Peter Vanbroekhoven

    # File lib/facets/comparable/cmp.rb, line 14
    def cmp(o)
      self<=>o
    end