End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
Range#max
static VALUE
range_max(int argc, VALUE *argv, VALUE range)
{
VALUE e = RANGE_END(range);
int nm = FIXNUM_P(e) || rb_obj_is_kind_of(e, rb_cNumeric);
if (NIL_P(RANGE_END(range))) {
rb_raise(rb_eRangeError, "cannot get the maximum of endless range");
}
VALUE b = RANGE_BEG(range);
if (rb_block_given_p() || (EXCL(range) && !nm) || argc) {
if (NIL_P(b)) {
rb_raise(rb_eRangeError, "cannot get the maximum of beginless range with custom comparison method");
}
return rb_call_super(argc, argv);
}
else {
struct cmp_opt_data cmp_opt = { 0, 0 };
int c = NIL_P(b) ? -1 : OPTIMIZED_CMP(b, e, cmp_opt);
if (c > 0)
return Qnil;
if (EXCL(range)) {
if (!RB_INTEGER_TYPE_P(e)) {
rb_raise(rb_eTypeError, "cannot exclude non Integer end value");
}
if (c == 0) return Qnil;
if (!RB_INTEGER_TYPE_P(b)) {
rb_raise(rb_eTypeError, "cannot exclude end value with non Integer begin value");
}
if (FIXNUM_P(e)) {
return LONG2NUM(FIX2LONG(e) - 1);
}
return rb_funcall(e, '-', 1, INT2FIX(1));
}
return e;
}
}
Returns the maximum value in the range, or an array of maximum values in the range if given an Integer argument.
For inclusive ranges with an end, the maximum value of the range is the same as the end of the range.
If an argument or block is given, or self is an exclusive, non-numeric range, calls Enumerable#max (via super) with the argument and/or block to get the maximum values, unless self is a beginless range, in which case it raises a RangeError.
If self is an exclusive, integer range (both start and end of the range are integers), and no arguments or block are provided, returns last value in the range (1 before the end). Otherwise, if self is an exclusive, numeric range, raises a TypeError.
Returns nil if the begin value of the range larger than the end value. Returns nil if the begin value of an exclusive range is equal to the end value. Raises a RangeError if called on an endless range.
Examples:
(10..20).max #=> 20 (10..20).max(2) #=> [20, 19] (10...20).max #=> 19 (10...20).max(2) #=> [19, 18] (10...20).max{|x, y| -x <=> -y } #=> 10 (10...20).max(2){|x, y| -x <=> -y } #=> [10, 11]