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 it require "set" # create a set Languages = Set.new(["Ruby", "PHP"]) # print previous elements puts "PREVIOUS ELEMENTS:\n" for element in Languages do puts element end # add elements to the set Languages.add("JavaScript") Languages.add("Java") Languages.add("Python") # print current elements puts "\nCURRENT ELEMENTS:" for element in Languages do puts element end
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.RELATED TAGS
CONTRIBUTOR
View all Courses