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.
set.each{|element|}
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.
The value returned is each element of the set. This allows us to perform any operation on them.
# require set classrequire("set")# create some setsEvenNumbers = 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 valueputs "Elements in EvenNumbers set"EvenNumbers.each{|e| puts e}# multiply each value by 2puts "\nElements in NumbersToTen set multiplied by 2"NumbersToTen.each{|e| puts e*2 }# print length of string of each worker's nameputs "\nLength of string of each worker's name"Workers.each{|e| puts(e, e.length)}
each{}
method, and print each element of the EvenNumbers
set to the console.each{}
method and print each element of the NumbersToTen
set to the console by multiplying each element by two.each{}
method, and print each name and the length of the string of the Workers
set to the console.