ruby-changes:71481
From: Jeremy <ko1@a...>
Date: Wed, 23 Mar 2022 23:56:02 +0900 (JST)
Subject: [ruby-changes:71481] 8f1c69f27c (master): Raise ArgumentError when calling Enumberable#inject without block or arguments
https://git.ruby-lang.org/ruby.git/commit/?id=8f1c69f27c From 8f1c69f27ce6b3f5ed1c1cf8d2aa62aa9701d636 Mon Sep 17 00:00:00 2001 From: Jeremy Evans <code@j...> Date: Tue, 22 Mar 2022 12:45:51 -0700 Subject: Raise ArgumentError when calling Enumberable#inject without block or arguments Previously, this would work as expected if the enumerable contained 0 or 1 element, and would raise LocalJumpError otherwise. That inconsistent behavior is likely to lead to bugs. Fixes [Bug #18635] --- enum.c | 10 +++++++++- test/ruby/test_enum.rb | 2 ++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/enum.c b/enum.c index 519d8873f6..383619999b 100644 --- a/enum.c +++ b/enum.c @@ -1010,8 +1010,16 @@ enum_inject(int argc, VALUE *argv, VALUE obj) https://github.com/ruby/ruby/blob/trunk/enum.c#L1010 VALUE init, op; rb_block_call_func *iter = inject_i; ID id; + int num_args; - switch (rb_scan_args(argc, argv, "02", &init, &op)) { + if (rb_block_given_p()) { + num_args = rb_scan_args(argc, argv, "02", &init, &op); + } + else { + num_args = rb_scan_args(argc, argv, "11", &init, &op); + } + + switch (num_args) { case 0: init = Qundef; break; diff --git a/test/ruby/test_enum.rb b/test/ruby/test_enum.rb index b0c43b9a7f..cc217b05cc 100644 --- a/test/ruby/test_enum.rb +++ b/test/ruby/test_enum.rb @@ -234,6 +234,8 @@ class TestEnumerable < Test::Unit::TestCase https://github.com/ruby/ruby/blob/trunk/test/ruby/test_enum.rb#L234 assert_equal(24, @obj.inject(2) {|z, x| z * x }) assert_equal(24, assert_warning(/given block not used/) {@obj.inject(2, :*) {|z, x| z * x }}) assert_equal(nil, @empty.inject() {9}) + + assert_raise(ArgumentError) {@obj.inject} end FIXNUM_MIN = RbConfig::LIMITS['FIXNUM_MIN'] -- cgit v1.2.1 -- ML: ruby-changes@q... Info: http://www.atdot.net/~ko1/quickml/