From 05bf811c2839628aaef3d565daedb28be80d47ef Mon Sep 17 00:00:00 2001 From: Jeremy Evans Date: Thu, 16 Jul 2020 10:11:35 -0700 Subject: Special case Range#max for integer beginning and Float::Infinity end Popular Ruby libraries such as Rails and Rubocop relying on the previous behavior, even though it is technically a bug. The correct behavior is probably raising RangeError, since that is what an endless range raises. Related to [Bug #17017] --- range.c | 9 +++++++++ test/ruby/test_range.rb | 6 ++++++ 2 files changed, 15 insertions(+) diff --git a/range.c b/range.c index 124d9faa51..6d507ea124 100644 --- a/range.c +++ b/range.c @@ -1255,6 +1255,15 @@ range_max(int argc, VALUE *argv, VALUE range) return rb_funcall(e, '-', 1, INT2FIX(1)); } if (RB_INTEGER_TYPE_P(b) && !RB_INTEGER_TYPE_P(e)) { + if (RB_TYPE_P(e, T_FLOAT)) { + VALUE inf = rb_funcall(e, rb_intern("infinite?"), 0); + if (inf != Qnil) { + /* For backwards compatibility, return end if the end + * is Float::Infinity and the beginning is integer. + If end is -Float::Infinity, return nil. */ + return(inf == INT2FIX(1) ? e : Qnil); + } + } e = rb_funcall(e, rb_intern("floor"), 0); } return e; diff --git a/test/ruby/test_range.rb b/test/ruby/test_range.rb index 0b3f6c68f6..0dc66445e9 100644 --- a/test/ruby/test_range.rb +++ b/test/ruby/test_range.rb @@ -131,6 +131,9 @@ class TestRange < Test::Unit::TestCase assert_equal(2, (..2).max) assert_raise(TypeError) { (...2).max } assert_raise(TypeError) { (...2.0).max } + + assert_equal(Float::INFINITY, (1..Float::INFINITY).max) + assert_nil((1..-Float::INFINITY).max) end def test_minmax @@ -157,6 +160,9 @@ class TestRange < Test::Unit::TestCase assert_equal(['a', 'c'], ('a'..'c').minmax) assert_equal(['a', 'b'], ('a'...'c').minmax) + + assert_equal([1, Float::INFINITY], (1..Float::INFINITY).minmax) + assert_equal([nil, nil], (1..-Float::INFINITY).minmax) end def test_initialize_twice -- cgit v1.2.3