How to clear all elements from a set in Ruby
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 setrequire "set"# create some setsEvenNumbers = 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 setsputs "#{EvenNumbers.to_a}"puts "#{NumbersToTen.to_a}"puts "#{Names.to_a}"puts "#{Workers.to_a}"# clear all elementsEvenNumbers.clearNumbersToTen.clearNames.clearWorkers.clear# print sets againputs "#{EvenNumbers.to_a}"puts "#{NumbersToTen.to_a}"puts "#{Names.to_a}"puts "#{Workers.to_a}"
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_amethod. - Line 17–20: We clear all elements of each set using the
clearmethod. - Line 23–26: We then print these sets again after they had been cleared of all their elements.