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]
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]
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments