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.
Set.add(element)
element
: This is the element we want to add to the set.
The value returned is a new set with the element
added to it.
# 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
require
to get the set class.for
loop to print the elements in the set we just created.add()
method of the set instance to add some elements to the set Languages
that we created.for
loop to print out the elements of the modified set.