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 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

Explanation

  • Line 2: We use require to 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 for loop 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 set Languages that we created.
  • Line 20–22: We again use the for loop to print out the elements of the modified set.

Free Resources