Module: Comparable

Included in:
Tuple
Defined in:
lib/core/facets/comparable/cap.rb,
lib/core/facets/comparable/cmp.rb,
lib/core/facets/comparable/clip.rb,
lib/core/facets/comparable/bound.rb,
lib/core/facets/comparable/op_get.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.[](*accessors) ⇒ Object

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


16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/core/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

Instance Method Details

#at_least(lower) ⇒ Object

Returns the lower of self or x.

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

CREDIT: Florian Gross



10
11
12
# File 'lib/core/facets/comparable/cap.rb', line 10

def at_least(lower)
  (self >= lower) ? self : lower
end

#at_most(upper) ⇒ Object Also known as: cap

Returns the greater of self or x.

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

CREDIT: Florian Gross



21
22
23
# File 'lib/core/facets/comparable/cap.rb', line 21

def at_most(upper)
  (self <= upper) ? self : upper
end

#bound(lower, upper = nil) ⇒ Object

Alias for Comparable#clamp. Reads more naturally in some contexts.

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


9
10
11
# File 'lib/core/facets/comparable/bound.rb', line 9

def bound(lower, upper=nil)
  upper ? clamp(lower, upper) : clamp(lower..)
end

#clip(lower, upper = nil) ⇒ Object

Deprecated.

Use Comparable#clamp instead (built-in since Ruby 2.4).



4
5
6
7
# File 'lib/core/facets/comparable/clip.rb', line 4

def clip(lower, upper=nil)
  warn "Comparable#clip is deprecated. Use Comparable#clamp instead.", uplevel: 1
  upper ? clamp(lower, upper) : clamp(lower..)
end

#cmp(o) ⇒ Object

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



14
15
16
# File 'lib/core/facets/comparable/cmp.rb', line 14

def cmp(o)
  self<=>o
end