From 874916c21db5e728ce84f5349a607c7ce42f6006 Mon Sep 17 00:00:00 2001 From: Charles OuGuo Date: Wed, 1 Feb 2023 21:13:30 -0500 Subject: [PATCH] In Ruby repeated fields, each_index actually iterates over the index, not the values --- .../v3.0.0/tests/repeated_field_test.rb | 14 ++++++++++++++ ruby/lib/google/protobuf/repeated_field.rb | 3 +-- ruby/tests/repeated_field_test.rb | 14 ++++++++++++++ 3 files changed, 29 insertions(+), 2 deletions(-) diff --git a/ruby/compatibility_tests/v3.0.0/tests/repeated_field_test.rb b/ruby/compatibility_tests/v3.0.0/tests/repeated_field_test.rb index caebde1db7..25b698c608 100755 --- a/ruby/compatibility_tests/v3.0.0/tests/repeated_field_test.rb +++ b/ruby/compatibility_tests/v3.0.0/tests/repeated_field_test.rb @@ -119,6 +119,20 @@ class RepeatedFieldTest < Test::Unit::TestCase assert_equal ['string'] * 5, result end + + def test_each_index + m = TestMessage.new + 5.times{|i| m.repeated_string << 'string' } + + expected = 0 + m.repeated_string.each_index do |idx| + assert_equal expected, idx + expected += 1 + assert_equal 'string', m.repeated_string[idx] + end + assert_equal 5, expected + end + def test_empty? m = TestMessage.new diff --git a/ruby/lib/google/protobuf/repeated_field.rb b/ruby/lib/google/protobuf/repeated_field.rb index 13b9300b2e..01dd814078 100644 --- a/ruby/lib/google/protobuf/repeated_field.rb +++ b/ruby/lib/google/protobuf/repeated_field.rb @@ -117,7 +117,6 @@ module Google end # array aliases into enumerable - alias_method :each_index, :each_with_index alias_method :slice, :[] alias_method :values_at, :select alias_method :map, :collect @@ -168,7 +167,7 @@ module Google end - %w(collect! compact! delete_if fill flatten! insert reverse! + %w(collect! compact! delete_if each_index fill flatten! insert reverse! rotate! select! shuffle! sort! sort_by! uniq!).each do |method_name| define_array_wrapper_with_result_method(method_name) end diff --git a/ruby/tests/repeated_field_test.rb b/ruby/tests/repeated_field_test.rb index de96869960..c7c2f24ef2 100755 --- a/ruby/tests/repeated_field_test.rb +++ b/ruby/tests/repeated_field_test.rb @@ -141,6 +141,20 @@ class RepeatedFieldTest < Test::Unit::TestCase end + def test_each_index + m = TestMessage.new + 5.times{|i| m.repeated_string << 'string' } + + expected = 0 + m.repeated_string.each_index do |idx| + assert_equal expected, idx + expected += 1 + assert_equal 'string', m.repeated_string[idx] + end + assert_equal 5, expected + end + + def test_empty? m = TestMessage.new assert_equal true, m.repeated_string.empty?