Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
communitycreator

How to check if a set is a proper subset of another set in Ruby

okwudili onyejiaku

Overview

A set is a collection of values that are unique but unordered. A set B is a proper subset of a set A if all the elements or values of B are present in A , while A also contains one or more elements that are not present in B.

To check if a set is a proper subset of another set, we can use the proper_subset() method in Ruby.

Syntax

set1.proper_subset(set2)
Syntax for proper_subset() in Ruby

Parameters

  • set1: This is the set we are checking to see if it is a proper subset of another set.
  • set2: This is the set to which we are comparing set1.

Return value

The returned value is a boolean value. We get true if set1 is a proper subset of set2. Otherwise, we get a false.

Code

# 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([])
Alphabets = Set.new(["a", "b", "c", "d", "e", "f", "g",
    "h", "i", "j", "k", "l", "m", "n", "o", "p", "q",
    "r", "s", "t", "u", "v", "w", "x", "y", "z"
])
Vowels = Set.new(["a", "e", "i", "o", "u"])

# check if proper subsets exists
puts NumbersToTen.proper_subset?(EvenNumbers) # false
puts Names.proper_subset?(Workers)            # true
puts EmptySet.proper_subset?(Names)           # true
puts Alphabets.proper_subset?(Vowels)         # false
Check if a set is a proper subset of another

Explanation

  • Line 2: We require the set class.
  • Lines 5–14: We create some sets.
  • Lines 17–20: We use the proper_subset?() method to check whether any proper subsets exist among the created sets. Then we print the results to the console.

RELATED TAGS

ruby
communitycreator
RELATED COURSES

View all Courses

Keep Exploring