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.
We can print the elements of a set by using the for
loop.
for element in Set do# do anything with "element"end
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.
The value returned is each element of the set.
# require the set Class to use itrequire "set"# create a setLanguages = Set.new(["Ruby", "PHP","JavaScript","Python"])for element in Languages doputs elementend
set
class. It is with it that we can create a set instance in Ruby.for
loop, we print each element of the set Language
to the console.We can use each
with do
to get the elements of a set.
The value returned is each element of the set.
# require the set Class to use itrequire "set"# create a setLanguages = Set.new(["Ruby", "PHP","JavaScript","Python"])# loop through the setLanguages.each do |element|#print each elementputs elementend
each
and do
methods, we print each element of the array.We can use each to get the elements of a set.
The value returned is each element of the set.
# require the set Class to use itrequire "set"# create a setLanguages = Set.new(["Ruby", "PHP","JavaScript","Python"])# loop through the setLanguages.each {|element| puts element}
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.