Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
communitycreator

What is difference() method of a set in Ruby?

okwudili onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

The difference() method of a set in Ruby is used to find the difference between two sets. This method returns a new set by duplicating the set that invokes it and by removing each of its elements that are also present in the other set. For example, if setA has the elements [1,2,3] and setB has the elements [2,3] and the `difference()` method is invoked with setA and setB as parameters, the returned result will be [1].

Syntax

set1.difference(set2)
Syntax of the "difference()" method

Parameter values

  • set1: This is the set that is duplicated and has its elements removed if they are also found in the other set, set2.
  • set2: This is the set we want to compare with the set set1.

Return value

The difference() method returns a new set that is a duplicate of set1.

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 difference
difference1 = NumbersToTen.difference(EvenNumbers)
difference2 = Workers.difference(Names)
# print out intersects
puts "#{difference1.to_a}"
puts "#{difference2.to_a}"
Using the "difference()" method on a set

Explanation

  • Line 2: We require the set class.
  • Lines 5–8: We create some set instances and initialize them.
  • Lines 11–12: We get the differences between some sets and store them in new variables.
  • Lines 15–16: We print these differences to the console.

RELATED TAGS

ruby
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring