Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
set
clear
communitycreator

How to clear all elements from a set in Ruby

okwudili onyejiaku

Overview

We use the clear() method to clear the elements of a set. The function helps remove all elements of the set.

Syntax

set.clear
Syntax for clear() method

Parameters

set: We aim to clear all elements of this set.

Return value

The value returned is the set excluding all of its elements.

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"])

# print sets
puts "#{EvenNumbers.to_a}"
puts "#{NumbersToTen.to_a}"
puts "#{Names.to_a}"
puts "#{Workers.to_a}"

# clear all elements
EvenNumbers.clear
NumbersToTen.clear
Names.clear
Workers.clear

# print sets again
puts "#{EvenNumbers.to_a}" 
puts "#{NumbersToTen.to_a}"
puts "#{Names.to_a}"
puts "#{Workers.to_a}"
Code for clear() method

Explanation

  • Line 2: We use require to obtain the set class.
  • Line 5–8: We create some sets and initialize them with some values.
  • Line 11–14: We print the sets to the console screen as an array by using the to_a method.
  • Line 17–20: We clear all elements of each set using the clear method.
  • Line 23–26: We then print these sets again after they had been cleared of all their elements.

RELATED TAGS

ruby
set
clear
communitycreator
RELATED COURSES

View all Courses

Keep Exploring