mruby-compar-ext (clamp): found a bug by newly added test

Translate CRuby's logic (in C) to Ruby.
This commit is contained in:
Yukihiro "Matz" Matsumoto
2024-11-26 12:00:00 +09:00
parent ec68c6afd8
commit c96f0cd265
+18 -35
View File
@@ -41,52 +41,35 @@ module Comparable
# 100.clamp(0...100) # ArgumentError
#
def clamp(min, max=nil)
if max.nil?
if min.kind_of?(Range)
max = min.end
if max.nil?
max = self
elsif min.exclude_end?
if !max.nil? && min.exclude_end?
raise ArgumentError, "cannot clamp with an exclusive range"
end
min = min.begin
if min.nil?
min = self
end
elsif min.nil? or min < self
return self
else
return min
end
end
if min.nil?
if self < max
return self
else
return max
if !min.nil? && !max.nil?
cmp = min <=> max
if cmp.nil?
raise ArgumentError, "comparison of #{min.class} with #{max.class} failed"
elsif cmp > 0
raise ArgumentError, "min argument must be smaller than max argument"
end
end
c = min <=> max
if c.nil?
raise ArgumentError, "comparison of #{min.class} with #{max.class} failed"
elsif c > 0
raise ArgumentError, "min argument must be smaller than max argument"
unless min.nil?
cmp = self <=> min
return self if cmp == 0
return min if cmp < 0
end
c = self <=> min
if c.nil?
raise ArgumentError, "comparison of #{self.class} with #{min.class} failed"
elsif c == 0
return self
elsif c < 0
return min
end
c = self <=> max
if c.nil?
raise ArgumentError, "comparison of #{self.class} with #{max.class} failed"
elsif c > 0
return max
else
return self
unless max.nil?
cmp = self <=> max
return max if cmp > 0
end
return self
end
end