Skip to content

Commit f869cfa

Browse files
shaldengekicopybara-github
authored andcommitted
In Ruby repeated fields, each_index actually iterates over the index (#11767)
Currently we're aliasing `each_index` to `each_with_index`, incorrectly passing both the index and the value of a repeated field to the block. What we want is to just pass the index. Luckily this is a method on Ruby arrays, so we just wrap the native Ruby array method. Fixes #7806 Closes #11767 COPYBARA_INTEGRATE_REVIEW=#11767 from shaldengeki:shaldengeki-repeated-field-each-index-returns-actual-index 874916c PiperOrigin-RevId: 593835025
1 parent da56def commit f869cfa

3 files changed

Lines changed: 29 additions & 2 deletions

File tree

ruby/compatibility_tests/v3.0.0/tests/repeated_field_test.rb

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,20 @@ def test_each
122122
end
123123

124124

125+
def test_each_index
126+
m = TestMessage.new
127+
5.times{|i| m.repeated_string << 'string' }
128+
129+
expected = 0
130+
m.repeated_string.each_index do |idx|
131+
assert_equal expected, idx
132+
expected += 1
133+
assert_equal 'string', m.repeated_string[idx]
134+
end
135+
assert_equal 5, expected
136+
end
137+
138+
125139
def test_empty?
126140
m = TestMessage.new
127141
assert_empty m.repeated_string

ruby/lib/google/protobuf/repeated_field.rb

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,6 @@ def empty?
9494
end
9595

9696
# array aliases into enumerable
97-
alias_method :each_index, :each_with_index
9897
alias_method :slice, :[]
9998
alias_method :values_at, :select
10099
alias_method :map, :collect
@@ -145,7 +144,7 @@ def define_array_wrapper_with_result_method(method_name)
145144
end
146145

147146

148-
%w(collect! compact! delete_if fill flatten! insert reverse!
147+
%w(collect! compact! delete_if each_index fill flatten! insert reverse!
149148
rotate! select! shuffle! sort! sort_by! uniq!).each do |method_name|
150149
define_array_wrapper_with_result_method(method_name)
151150
end

ruby/tests/repeated_field_test.rb

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,20 @@ def test_each
143143
end
144144

145145

146+
def test_each_index
147+
m = TestMessage.new
148+
5.times{|i| m.repeated_string << 'string' }
149+
150+
expected = 0
151+
m.repeated_string.each_index do |idx|
152+
assert_equal expected, idx
153+
expected += 1
154+
assert_equal 'string', m.repeated_string[idx]
155+
end
156+
assert_equal 5, expected
157+
end
158+
159+
146160
def test_empty?
147161
m = TestMessage.new
148162
assert_empty m.repeated_string

0 commit comments

Comments
 (0)