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 itrequire "set"# create a setLanguages = Set.new(["Ruby", "Java", "PHP", "JavaScript", "Python"])# print previous elementsputs "PREVIOUS ELEMENTS:\n"for element in Languages doputs elementend# delete some elements from the setLanguages.delete("JavaScript")Languages.delete("Java")Languages.delete("Python")# print current elementsputs "\nCURRENT ELEMENTS:"for element in Languages doputs elementend
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
forloop, 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 setLanguagesthat we created. - Line 20: Once again, with the
forloop, we print out the elements of the modified set.