What is set.replace() method in Ruby?

Overview

The replace() method of a set is used to replace the set's contents. The contents of the set are replaced with new content that we specify. The content that will replace the previous one is an enumerable object, for example, an array.

Syntax

set.replace(object)
syntax for replace() method in Ruby

Parameters

object: This is the object containing the elements that will replace the elements or contents of the set.

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])
Developers = Set.new(["Amaka", "Chioma", "Titi"])
# check if proper supersets exists
EvenNumbers.replace([24])
NumbersToTen.replace([30, 22, 4, 1])
Developers.replace(["Peter", "Jane"])
# print sets
puts "#{EvenNumbers.to_a}"
puts "#{NumbersToTen.to_a}"
puts "#{Developers.to_a}"

Explanation

  • Line 2: We require the set class for all set operations.
  • Line 5–7: We create some sets.
  • Line 10–12: Using the replace() method, we replace the contents of the set with some new values.
  • Line 15–17: We print the results of the modified sets in an array form.

Free Resources