Module: Comparable

Defined in:
lib/nano/comparable/cap.rb,
lib/nano/comparable/cmp.rb,
lib/nano/comparable/clip.rb,
lib/nano/comparable/at_most.rb,
lib/nano/comparable/at_least.rb

Overview

– Credit goes to Florian Gross. ++

Instance Method Summary collapse

Instance Method Details

#at_least(x) ⇒ Object

Returns the lower of self or x.

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


10
11
12
# File 'lib/nano/comparable/at_least.rb', line 10

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

#at_most(x) ⇒ Object

Returns the greater of self or x.

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


10
11
12
# File 'lib/nano/comparable/at_most.rb', line 10

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

#cap(x) ⇒ Object

Returns the greater of self or x.

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


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

def cap(x)
  (self <= x) ? self : x
end

#clip(lower, upper = nil) ⇒ Object

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


16
17
18
19
20
21
# File 'lib/nano/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

#cmp(o) ⇒ Object

Alternate name for comparison operator #<=>.

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


9
10
11
# File 'lib/nano/comparable/cmp.rb', line 9

def cmp(o)
  self<=>o
end