Ruby | Array intersection operation
Last Updated :
07 Jan, 2020
Array#&() is a Array class method which performs set intersection operation on the arrays. And returns the common of the two arrays.
Syntax: Array.&()
Parameter: Arrays for performing the intersection operation.
Return: Common elements from both the arrays.
Example #1 :
a = [ 18 , 22 , 33 , 4 , 5 , 6 ]
b = [ 5 , 4 , 22 , 1 , 88 , 9 ]
c = [ 18 , 22 , 33 , 40 , 50 , 6 ]
puts "intersection of a and b : #{a & b}\n\n"
puts "intersection of a and c : #{a & c}\n\n"
puts "intersection of b and c : #{b & c}\n\n"
|
Output :
intersection of a and b : [22, 4, 5]
intersection of a and c : [18, 22, 33, 6]
intersection of b and c : [22]
Example #2 :
a = [ "abc" , "xyz" , "dog" ]
b = [ "cow" , "cat" , "dog" ]
c = [ "cat" , "1" , "dog" ]
puts "intersection of a and b : #{a & b}\n\n"
puts "intersection of a and c : #{a & c}\n\n"
puts "intersection of b and c : #{b & c}\n\n"
|
Output :
intersection of a and b : ["dog"]
intersection of a and c : ["dog"]
intersection of b and c : ["cat", "dog"]
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...