0

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?

2
  • can't you do (elements & other).size? Commented Sep 24, 2013 at 13:11
  • @j03W It doesn't compare 2 elements with same index as a pair, but returns an intersection of 2 arrays. Commented Sep 24, 2013 at 15:00

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

That's the answer I was looking for!
2

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

2 Comments

Good point. This is the most natural solution to the problem but I was asking about each_with_index.with_object
You're right, it doesn't answer it. I just wanted to add an alternative because your approach looked a bit complicated :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.