我正在尝试迭代一个数组并有条件地增加一个计数器。我正在使用索引与其他数组的元素进行比较:
elements.each_with_index.with_object(0) do |(element, index), diff|
diff += 1 unless other[index] == element
end
diff
即使无条件地改变它,我也无法改变它。这可以通过以下方式解决inject
:
elements.each_with_index.inject(0) do |diff, (element, index)|
diff += 1 unless other[index] == element
diff
end
但我想知道是否.each_with_index.with_object(0)
是一个有效的结构以及如何使用它?