Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
set
subset
communitycreator

How to find a subset of set1 and set2 in Ruby using < operator

okwudili onyejiaku

Overview

In Ruby, we use the less-than operator < to determine if a particular set is a subset of another. If set1 is a subset of set2, then all the elements of set1 are present in set2. Remember that a set is a collection of unordered values without duplicates.

Syntax

set1 < set2
Syntax to check if a set is a subset of another in Ruby

Parameters

set1: This is the set for which we want to check if it is the subset of set2.

set2: This is the set for which we want to check if set1 is its subset.

Return value

A Boolean value is returned, which tells that set1 is a subset of sub2. If it is a subset then a true is returned, otherwise false.

Example

# require set
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"])

# get the intersection
puts EvenNumbers < NumbersToTen  # true
puts Workers < Names             # false
Check if a set is a subset of another in Ruby

Explanation

  • Line 2: We use require to get the set class.
  • Line 5–8: We create some new sets and initialize them with some values.
  • Line 11–12: We use the < operator to check if some sets were subsets for another.

RELATED TAGS

ruby
set
subset
communitycreator
RELATED COURSES

View all Courses

Keep Exploring