What is set.each{} in Ruby?

Overview

In Ruby, a set is a collection of unordered data that is similar, unique, and can't be duplicated. The each{} method in Ruby comes in handy when we want to map through a set and perform an operation on the elements of the set. It uses its block to yield each element. This way we can have access to each element of the set.

Syntax

set.each{|element|}
Syntax for each{} method of a set

Parameters

element: This represents each element of the set. It is taken as a parameter by the each{} block and makes each element of the set available so that we can carry out any operation on them, such as printing to the console.

Return value

The value returned is each element of the set. This allows us to perform any operation on them.

Code example

# require set class
require("set")
# create some sets
EvenNumbers = Set.new([2, 4, 6, 8, 10])
NumbersToTen = Set.new([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
Workers = Set.new(["Chisom", "Chioma", "Titi"])
# print each value
puts "Elements in EvenNumbers set"
EvenNumbers.each{|e| puts e}
# multiply each value by 2
puts "\nElements in NumbersToTen set multiplied by 2"
NumbersToTen.each{|e| puts e*2 }
# print length of string of each worker's name
puts "\nLength of string of each worker's name"
Workers.each{|e| puts(e, e.length)}

Explanation

  • Line 2: We require the set class.
  • Lines 5–7: We create and initialize three set instances.
  • Line 11: We use the each{} method, and print each element of the EvenNumbers set to the console.
  • Line 15: We use the each{} method and print each element of the NumbersToTen set to the console by multiplying each element by two.
  • Line 19: We use the each{} method, and print each name and the length of the string of the Workers set to the console.

Free Resources