Module: Comparable

Included in:
Numeric, String, Symbol
Defined in:
mrblib/compar.rb,
mrbgems/mruby-compar-ext/mrblib/compar.rb

Overview

Comparable

ISO 15.3.3

Instance Method Summary collapse

Instance Method Details

#<(other) ⇒ Object

Return true if +self+ is less than +other+. Otherwise return false.

ISO 15.3.3.2.1



13
14
15
16
17
18
19
# File 'mrblib/compar.rb', line 13

def < other
  cmp = self <=> other
  if cmp.nil?
    raise ArgumentError, "comparison of #{self.class} with #{other.class} failed"
  end
  cmp < 0
end

#<=(other) ⇒ Object

Return true if +self+ is less than or equal to +other+. Otherwise return false.

ISO 15.3.3.2.2



27
28
29
30
31
32
33
# File 'mrblib/compar.rb', line 27

def <= other
  cmp = self <=> other
  if cmp.nil?
    raise ArgumentError, "comparison of #{self.class} with #{other.class} failed"
  end
  cmp <= 0
end

#==(other) ⇒ Object

Return true if +self+ is equal to +other+. Otherwise return false.

ISO 15.3.3.2.3



41
42
43
44
# File 'mrblib/compar.rb', line 41

def == other
  cmp = self <=> other
  cmp == 0
end

#>(other) ⇒ Object

Return true if +self+ is greater than +other+. Otherwise return false.

ISO 15.3.3.2.4



52
53
54
55
56
57
58
# File 'mrblib/compar.rb', line 52

def > other
  cmp = self <=> other
  if cmp.nil?
    raise ArgumentError, "comparison of #{self.class} with #{other.class} failed"
  end
  cmp > 0
end

#>=(other) ⇒ Object

Return true if +self+ is greater than or equal to +other+. Otherwise return false.

ISO 15.3.3.2.5



66
67
68
69
70
71
72
# File 'mrblib/compar.rb', line 66

def >= other
  cmp = self <=> other
  if cmp.nil?
    raise ArgumentError, "comparison of #{self.class} with #{other.class} failed"
  end
  cmp >= 0
end

#between?(min, max) ⇒ Boolean

Return true if +self+ is greater than or equal to +min+ and less than or equal to +max+. Otherwise return false.

ISO 15.3.3.2.6

Returns:

  • (Boolean)


81
82
83
# File 'mrblib/compar.rb', line 81

def between?(min, max)
  self >= min and self <= max
end

#clamp(min, max) ⇒ Object

Returns min if obj <=> min is less than zero, max if obj <=> max is greater than zero and obj otherwise.

12.clamp(0, 100)         #=> 12
523.clamp(0, 100)        #=> 100
-3.123.clamp(0, 100)     #=> 0

'd'.clamp('a', 'f')      #=> 'd'
'z'.clamp('a', 'f')      #=> 'f'


14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'mrbgems/mruby-compar-ext/mrblib/compar.rb', line 14

def clamp(min, max)
  if (min <=> max) > 0
    raise ArgumentError, "min argument must be smaller than max argument"
  end
  c = self <=> min
  if c == 0
    return self
  elsif c < 0
    return min
  end
  c = self <=> max
  if c > 0
    return max
  else
    return self
  end
end