danynl danynl - 1 year ago 109
Ruby Question

Compare arrays with index ruby

I am trying to get the differences between two arrays of equal length in ruby.

array1 = [1,2,3,4]

array2 = [1,2,4,5]

diffArray = []
diffArray = array1 - array2 # => [3]


But I would like to save the index at which the differences occur relative to
array1
or
array2
. For example, I would like
diffArray
to be saved as

#diffArray => [nil,nil,3,nil]
or
#diffArray => ["","",3,""]


Is there a way to do this in ruby?

Answer Source

I would do something like this:

array1 = [1,2,3,4]
array2 = [1,2,4,5]

array1.zip(array2).map { |a, b| a if a != b }
#=> [nil, nil, 3, 4]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download