Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
communitycreator

How to take union of two sets in Ruby

okwudili onyejiaku

Overview

The addition of two sets in Ruby results in the union A union of two sets is a new set with elements of both setsof two sets. Therefore, the union of set1 and set2 is a new set containing elements of set1 and set2. This is made possible using the plus operator, +.

Note: Sets do not accommodate duplicate values or elements.

Syntax

set1 + set2
Get the union of two sets

Operands

set1 and set2: These are the sets we want to get the union of.

Return value

It returns a new set with elements of set1 and set2.

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 union
Union1 = EvenNumbers + NumbersToTen
Union2 = Names + Workers

# print out intersects
puts "#{Union1.to_a}"
puts "#{Union2.to_a}"
Get the union of two sets in Ruby

Explanation

  • Line 2: We import the set instance.
  • Lines 5–8: We create some set instances and initialize them.
  • Lines 11 and 12: We use the + operator to take the union of set instances.
  • Lines 15 and 16: We print the unions in an array format to the console.

RELATED TAGS

ruby
communitycreator
RELATED COURSES

View all Courses

Keep Exploring