How to add element to a set in Ruby
Overview
A set is a data structure used to store elements or values that must be unique. In this shot, we will look at adding elements to a set in Ruby by using method add() with the set instance.
Syntax
Set.add(element)
Syntax of add() method of a set in Ruby
Parameters
element: This is the element we want to add to the set.
Return value
The value returned is a new set with the element added to it.
Example
# require the set Class to use itrequire "set"# create a setLanguages = Set.new(["Ruby", "PHP"])# print previous elementsputs "PREVIOUS ELEMENTS:\n"for element in Languages doputs elementend# add elements to the setLanguages.add("JavaScript")Languages.add("Java")Languages.add("Python")# print current elementsputs "\nCURRENT ELEMENTS:"for element in Languages doputs elementend
Explanation
- Line 2: We use
requireto get the set class. - Line 5: We create a new set instance and initialize it with some values or elements.
- Line 9: We use the
forloop to print the elements in the set we just created. - Line 14–16: We use the
add()method of the set instance to add some elements to the setLanguagesthat we created. - Line 20–22: We again use the
forloop to print out the elements of the modified set.