How to delete an element from a Set in Ruby?

Overview

Removing or deleting an element from a Set in Ruby is easy to do by using the delete() method. This method takes the element we want to remove as a parameter.

Syntax

set.delete(element)
delete() syntax of a set in Ruby

Parameters

element: This is the element we want to delete from the set.

Return value

A new array is returned with element removed.

Code example

# require the set Class to use it
require "set"
# create a set
Languages = Set.new(["Ruby", "Java", "PHP", "JavaScript", "Python"])
# print previous elements
puts "PREVIOUS ELEMENTS:\n"
for element in Languages do
puts element
end
# delete some elements from the set
Languages.delete("JavaScript")
Languages.delete("Java")
Languages.delete("Python")
# print current elements
puts "\nCURRENT ELEMENTS:"
for element in Languages do
puts element
end

Explanation

  • Line 2: Require the set class.
  • Line 5: A new set instance was created and we initialize it with some values or elements.
  • Line 9: With the aid of the for loop, we print the elements in the set we just created.
  • Lines 14-16: With the delete() method of the set instance, we deleted some elements to the set Languages that we created.
  • Line 20: Once again, with the for loop, we print out the elements of the modified set.

Free Resources