Skip to main content

Ruby Set intersection() method

In ruby programming language, intersection() set methods are used to select sets and enumerable objects with a common element. The syntax of this method as follows.

set.intersection(enum) -> new set

This method are accept an enumerable object and returning a new set. The resultant set contains distinct common objects. When set and enumerable object are no common objects then this method returns an empty set.

Ruby intersection method example

require "set"
# Set s1
s1 = Set[10,20,['a', 'b'],true]
# Set s2
s2 = Set[40,30,10]

# Set s3
# Intersection of s1 and s2 set
s3 = s1.intersection(s2)

# Intersection of s1 set and enumerable object
s4 = s2.intersection([40,60,10])

# Display result
print("\ns1 : ",s1.to_a)
print("\ns2 : ",s2.to_a)
print("\ns3 : ",s3.to_a)
print("\ns4 : ",s4.to_a)
Ruby intersection set method example 1

s1 : [10, 20, ["a", "b"], true]
s2 : [40, 30, 10]
s3 : [10]
s4 : [40, 10]


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment