Debian Codegraph @

vendor/mruby-source/mrbgems/mruby-compar-ext/mrblib/compar.rb

raw
1 module Comparable
2 ##
3 # call-seq:
4 # obj.clamp(min, max) -> obj
5 # obj.clamp(range) -> obj
6 #
7 # In <code>(min, max)</code> form, returns _min_ if _obj_
8 # <code><=></code> _min_ is less than zero, _max_ if _obj_
9 # <code><=></code> _max_ is greater than zero, and _obj_
10 # otherwise.
11 #
12 # 12.clamp(0, 100) #=> 12
13 # 523.clamp(0, 100) #=> 100
14 # -3.123.clamp(0, 100) #=> 0
15 #
16 # 'd'.clamp('a', 'f') #=> 'd'
17 # 'z'.clamp('a', 'f') #=> 'f'
18 #
19 # In <code>(range)</code> form, returns _range.begin_ if _obj_
20 # <code><=></code> _range.begin_ is less than zero, _range.end_
21 # if _obj_ <code><=></code> _range.end_ is greater than zero, and
22 # _obj_ otherwise.
23 #
24 # 12.clamp(0..100) #=> 12
25 # 523.clamp(0..100) #=> 100
26 # -3.123.clamp(0..100) #=> 0
27 #
28 # 'd'.clamp('a'..'f') #=> 'd'
29 # 'z'.clamp('a'..'f') #=> 'f'
30 #
31 # If _range.begin_ is +nil+, it is considered smaller than _obj_,
32 # and if _range.end_ is +nil+, it is considered greater than
33 # _obj_.
34 #
35 # -20.clamp(0..) #=> 0
36 # 523.clamp(..100) #=> 100
37 #
38 # When _range.end_ is excluded and not +nil+, an exception is
39 # raised.
40 #
41 # 100.clamp(0...100) # ArgumentError
42 #
43 def clamp(min, max=nil)
44 if max.nil?
45 if min.kind_of?(Range)
46 max = min.end
47 if max.nil?
48 max = self
49 elsif min.exclude_end?
50 raise ArgumentError, "cannot clamp with an exclusive range"
51 end
52 min = min.begin
53 if min.nil?
54 min = self
55 end
56 elsif min.nil? or min < self
57 return self
58 else
59 return min
60 end
61 end
62 if min.nil?
63 if self < max
64 return self
65 else
66 return max
67 end
68 end
69 c = min <=> max
70 if c.nil?
71 raise ArgumentError, "comparison of #{min.class} with #{max.class} failed"
72 elsif c > 0
73 raise ArgumentError, "min argument must be smaller than max argument"
74 end
75 c = self <=> min
76 if c.nil?
77 raise ArgumentError, "comparison of #{self.class} with #{min.class} failed"
78 elsif c == 0
79 return self
80 elsif c < 0
81 return min
82 end
83 c = self <=> max
84 if c.nil?
85 raise ArgumentError, "comparison of #{self.class} with #{max.class} failed"
86 elsif c > 0
87 return max
88 else
89 return self
90 end
91 end
92 end