For example
a = [2,3,1,1]
b = [2,7,4,2]
--> c = [2]
My solution was:
c = b.select do
|em| b.index(em) == a.index(em)
end
But if I apply it to the given example it returns
c = [2,2]
CodePudding user response:
Since you want to compare arrays element-wise, zip
would be an excellent choice here.
a.zip(b) # => [[2, 2], [3, 7], [1, 4], [1, 2]]
a.zip(b).select {|a1, b1| a1 == b1}.map(&:first) # [2]
# or in ruby 2.7
a.zip(b).filter_map {|a1, b1| a1 == b1 && a1} # [2]
CodePudding user response:
a = [2,3,1,1]
b = [2,7,4,2]
c = b.select do |em|
b.index(em) == a.index(em)
end
b.select do |em|
takes the first element of b (which is 2). b.index(em)
finds the first index which contains a 2, which is the first one. (index 0). Since array a has a 2 on the same index, the whole block is true and the element 2 is selected. But the same story is true for the last element. Again, the b array is searched and the first 2 is found at index 0. Hence, that 2 is also selected.
a.each_with_index.to_a & b.each_with_index.to_a
woud give you the common element(s) and their indices.