Commit 0ad5ba7a authored by Ryan Lopopolo's avatar Ryan Lopopolo

Add a fast path for Float and Fixnum ranges for Range#max and Range#min

If no block is given and the Range has Fixnum or Float endpoints, do not iterate with
each and instead compare the endpoints directly. This implementation passes all of
the applicable specs from Ruby Spec.
parent eab07daf
......@@ -25,4 +25,44 @@ class Range
end
ary
end
def max(&block)
val = self.first
last = self.last
return super if block
# fast path for numerics
if (val.kind_of?(Fixnum) || val.kind_of?(Float)) && (last.kind_of?(Fixnum) || last.kind_of?(Float))
raise TypeError if exclude_end? && !last.kind_of?(Fixnum)
return nil if val > last
return nil if val == last && exclude_end?
max = last
max -= 1 if exclude_end?
return max
end
# delegate to Enumerable
super
end
def min(&block)
val = self.first
last = self.last
return super if block
# fast path for numerics
if (val.kind_of?(Fixnum) || val.kind_of?(Float)) && (last.kind_of?(Fixnum) || last.kind_of?(Float))
raise TypeError if exclude_end? && !last.kind_of?(Fixnum)
return nil if val > last
return nil if val == last && exclude_end?
min = val
min -= 1 if exclude_end?
return min
end
# delegate to Enumerable
super
end
end
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment