How to print elements of a Set in Ruby with loops

Overview

A set is a sequence of unique elements. It is similar to an array. The only difference is that a set elements must be unique and have no duplicate values.

Using a for loop

We can print the elements of a set by using the for loop.

Syntax

for element in Set do
# do anything with "element"
end
Syntax of for loop

Parameters

element: This represents each element of the set. It is provided to us by the for loop. Hence, inside the loop's body, we can do anything we want to do.

Return value

The value returned is each element of the set.

Code example

# require the set Class to use it
require "set"
# create a set
Languages = Set.new(["Ruby", "PHP","JavaScript","Python"])
for element in Languages do
puts element
end

Explanation

  • Line 2: We require the set class. It is with it that we can create a set instance in Ruby.
  • Line 5: We create a new set instance and initialize it with some elements.
  • Line 7: By using the for loop, we print each element of the set Language to the console.

Using each with do

We can use each with do to get the elements of a set.

Return value

The value returned is each element of the set.

Code example

# require the set Class to use it
require "set"
# create a set
Languages = Set.new(["Ruby", "PHP","JavaScript","Python"])
# loop through the set
Languages.each do |element|
#print each element
puts element
end

Explanation

  • Line 2: We require the set class.
  • Line 5: We create a new set and initialize it.
  • Line 8: Using the each and do methods, we print each element of the array.

Using each

We can use each to get the elements of a set.

Return value

The value returned is each element of the set.

Code example

# require the set Class to use it
require "set"
# create a set
Languages = Set.new(["Ruby", "PHP","JavaScript","Python"])
# loop through the set
Languages.each {|element| puts element}

Explanation

  • Line 2: We import or require the set class.
  • Line 5: We create a new set and initialize it.
  • Line 8: Using the predefined method of a set each{} we print each element of the set. This method uses a block which then takes each element as a parameter. With this, we can then print the elements of the set.

Free Resources