简体   繁体   中英

How do I do element-wise comparison of two arrays?

I have two arrays:

a = [1,2,3]
b = [1,4,3]

Is there an element-wise comparison method in Ruby such that I could do something like this:

a == b

returns:

[1,0,1] or something like [TRUE,FALSE,TRUE] .

Here's one way that I can think of.

a = [1, 2, 3]
b = [1, 4, 3]

a.zip(b).map { |x, y| x == y } # [true, false, true]

You can also use .collect

a.zip(b).collect {|x,y| x==y }
=> [true, false, true]
a = [1,2,3]
b = [1,4,3]
a.zip(b).map { |pair| pair[0] <=> pair[1] }
=> [0, -1, 0]

The element-wise comparison is achieved with the zip Ruby Array object method.

a = [1,2,3]
b = [1,4,3]
a.zip(b)
=> [[1, 1], [2, 4], [3, 3]]

You can do something like this to get exactly what you want:

[1,2,3].zip([1,4,3]).map { |a,b| a == b }
=> [true, false, true]

This should do the trick:

array1.zip(array2).map { |a, b| a == b }

zip creates one array of pairs consisting of each element from both arrays at that position. Imagine gluing the two arrays side by side.

Try something like this :

@array1 = ['a', 'b', 'c', 'd', 'e']
@array2 = ['d', 'e', 'f', 'g', 'h']
@intersection = @array1 & @array2

@intersection should now be ['d', 'e'].

Intersection—Returns a new array containing elements common to the two arrays, with no duplicates.

You can even try some of the ruby tricks like the following :

array1 = ["x", "y", "z"]  
array2 = ["w", "x", "y"]  
array1 | array2 # Combine Arrays & Remove Duplicates(Union)  
=> ["x", "y", "z", "w"]  

array1 & array2  # Get Common Elements between Two Arrays(Intersection)  
=> ["x", "y"]  


array1 - array2  # Remove Any Elements from Array 1 that are 
                 # contained in Array 2 (Difference)  
=> ["z"]  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM