Reputation: 12073
I am trying to iterate over an array and conditionally increment a counter. I am using index to compare to other array's elements:
elements.each_with_index.with_object(0) do |(element, index), diff|
diff += 1 unless other[index] == element
end
I can't get diff
to change value even when changing it unconditionally.
This can be solved with inject
:
elements.each_with_index.inject(0) do |diff, (element, index)|
diff += 1 unless other[index] == element
diff
end
But I am wondering if .each_with_index.with_object(0)
is a valid construction and how to use it?
Upvotes: 0
Views: 2548
Reputation: 114248
You want to count the number of element wise differences, right?
elements = [1, 2, 3, 4, 5]
other = [1, 2, 0, 4, 5]
# ^
I'd use Array#zip
to combine both arrays element wise and Array#count
to count the unequal pairs:
elements.zip(other).count { |a, b| a != b } #=> 1
Upvotes: 2
Reputation: 8003
From ruby docs for each_with_object
Note that you can’t use immutable objects like numbers, true or false as the memo. You would think the following returns 120, but since the memo is never changed, it does not.
(1..5).each_with_object(1) { |value, memo| memo *= value } # => 1
So each_with_object
does not work on immutable objects like integer.
Upvotes: 6