#--
# Credit goes to Florian Gross.
#++
module Comparable

  # 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
  #
  def clip(lower, upper=nil)
    return lower if self < lower
    return self unless upper
    return upper if self > upper
    return self
  end

  # Returns the greater of self or x.
  #
  #   4.cap(5)  #=> 4
  #   6.cap(5)  #=> 5
  #
  def cap(upper)
    (self <= upper) ? self : upper
  end

end


#  _____         _
# |_   _|__  ___| |_
#   | |/ _ \/ __| __|
#   | |  __/\__ \ |_
#   |_|\___||___/\__|
#
=begin test

  require 'test/unit'

  class TCComparable < Test::Unit::TestCase

    def test_clip
      assert_equal( 4, 3.clip(4) )
      assert_equal( 4, 4.clip(4) )
      assert_equal( 5, 5.clip(4) )
      assert_equal( 4, 4.clip(3,5) )
      assert_equal( 3, 3.clip(3,5) )
      assert_equal( 5, 5.clip(3,5) )
      assert_equal( 3, 2.clip(3,5) )
      assert_equal( 5, 6.clip(3,5) )
      assert_equal( 'd', 'd'.clip('c','e') )
      assert_equal( 'c', 'c'.clip('c','e') )
      assert_equal( 'e', 'e'.clip('c','e') )
      assert_equal( 'c', 'b'.clip('c','e') )
      assert_equal( 'e', 'f'.clip('c','e') )
    end

    def test_cap
      assert_equal( 3, 3.cap(4) )
      assert_equal( 4, 4.cap(4) )
      assert_equal( 4, 5.cap(4) )
    end

  end

=end
