1
0
Fork 0
mirror of https://github.com/ruby/ruby.git synced 2022-11-09 12:17:21 -05:00

range.c: Range#to_a now raises RangeError if it is endless

Fixes [Bug #14845]

git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@63714 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
This commit is contained in:
mame 2018-06-22 02:58:37 +00:00
parent 3afb77330f
commit c19ecf05b4
2 changed files with 28 additions and 0 deletions

22
range.c
View file

@ -755,6 +755,26 @@ range_size(VALUE range)
return Qnil;
}
/*
* call-seq:
* rng.to_a -> array
* rng.entries -> array
*
* Returns an array containing the items in <i>rng</i>.
*
* (1..7).to_a #=> [1, 2, 3, 4, 5, 6, 7]
* (1..).to_a #=> RangeError: cannot convert endless range to an array
*/
static VALUE
range_to_a(VALUE range)
{
if (NIL_P(RANGE_END(range))) {
rb_raise(rb_eRangeError, "cannot convert endless range to an array");
}
return rb_call_super(0, 0);
}
static VALUE
range_enum_size(VALUE range, VALUE args, VALUE eobj)
{
@ -1459,6 +1479,8 @@ Init_Range(void)
rb_define_method(rb_cRange, "min", range_min, -1);
rb_define_method(rb_cRange, "max", range_max, -1);
rb_define_method(rb_cRange, "size", range_size, 0);
rb_define_method(rb_cRange, "to_a", range_to_a, 0);
rb_define_method(rb_cRange, "entries", range_to_a, 0);
rb_define_method(rb_cRange, "to_s", range_to_s, 0);
rb_define_method(rb_cRange, "inspect", range_inspect, 0);

View file

@ -794,4 +794,10 @@ class TestRange < Test::Unit::TestCase
end
(a.."c").each {|x, &b| assert_nil(b)}
end
def test_to_a
assert_equal([1,2,3,4,5], (1..5).to_a)
assert_equal([1,2,3,4], (1...5).to_a)
assert_raise(RangeError) { (1..).to_a }
end
end