morrime - 1 month ago 6x

Ruby Question

I'm trying to count the differences between two arrays where the order DOES matter. For example:

`array_one = ["A", "B", "C"]`

array_two = ["B", "C", "A"]

This would yield 3 differences because:

`array_one[0] != array_two[0]`

array_one[1] != array_two[1]

array_one[2] != array_two[2]

Another example:

`array_one = ["Z", "X", "Y"]`

array_two = ["Z", "W", "Y"]

This would yield 1 because:

`array_one[0] == array_two[0]`

array_one[1] != array_two[1]

array_one[2] == array_two[2]

Any suggestions greatly appreciated.

Answer

how about this

```
array_one = ["A", "B", "C"]
array_two = ["A", "C", "A"]
array_one.select.each_with_index { |item, index|
array_two[index] != item
} => #B and C
```

Source (Stackoverflow)

Comments