What is the intersect?() method in Ruby?

Overview

In Ruby, the intersect?() method is used to check to see if two sets have an intersection. If they do, then this method returns a true value. Else, it returns false.

Syntax

set1.intersect?(set2)
Syntax for the intersect?() method in Ruby

Parameters

The set1 and set2 are sets we want to check if they have any intersection (common elements).

Return value

It returns a boolean value, true, if there is an intersection. Otherwise, it returns false.

Example

# require the set class
require "set"
# create some sets
EvenNumbers = Set.new([2, 4, 6, 8, 10])
NumbersToTen = Set.new([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
Names = Set.new(["Amaka", "Titi"])
Workers = Set.new(["Amaka", "Chioma", "Titi"])
EmptySet = Set.new([])
# check if intersections exists
puts EvenNumbers.intersect?(NumbersToTen) # true
puts Names.intersect?(Workers) # true
puts EvenNumbers.intersect?(EmptySet) # false
puts Names.intersect?(EmptySet) # false

Explanation

  • Line 2: We import the set class.
  • Lines 5–9: We create some set instances and initialized them. We create an empty set too.
  • Lines 12–15: We use the intersect?() method to check to see if some of the sets have intersections. Next, we print the returned result to the console.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources