Ruby | Array intersection operation

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 :



filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby code for &() method
# showing intersection operation
   
# declaration of array
a = [18, 22, 33, 4, 5, 6]
   
# declaration of array
b = [5, 4, 22, 1, 88, 9]
   
# declaration of array
c = [18, 22, 33, 40, 50, 6]
   
# a intersecting b
puts "intersection of a and b : #{a & b}\n\n"
   
# a intersecting c
puts "intersection of a and c : #{a & c}\n\n"
   
# b intersecting c
puts "intersection of b and c : #{b & c}\n\n"

chevron_right


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 :

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby code for &() method
# showing intersection operation
   
# declaration of array
a = ["abc", "xyz", "dog"]
   
# declaration of array
b = ["cow", "cat", "dog"]
   
# declaration of array
c = ["cat", "1", "dog"]
   
# a intersecting b
puts "intersection of a and b : #{a & b}\n\n"
   
# a intersecting c
puts "intersection of a and c : #{a & c}\n\n"
   
# b intersecting c
puts "intersection of b and c : #{b & c}\n\n"

chevron_right


Output :

intersection of a and b : ["dog"]

intersection of a and c : ["dog"]

intersection of b and c : ["cat", "dog"]



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.