Home »
Ruby »
Ruby Programs
Print the elements of a set in Ruby
Printing the element of a set: Here, we are going to learn how to print the elements of a set in Ruby programming language?
Submitted by Hrithik Chandra Prasad, on October 14, 2019
We have gone through the implementation of sets in Ruby. They are very similar to arrays. Now, let us see how we print the elements present in a set. There are no indexes present in the sets because sets are used to store the large elements.
Methods used:
- set.add(): This method is used to add the elements in the set. It would only add the elements which are not present in the set. You will not get an error if you try to add duplicate elements but duplicate elements will not be reflected in the set.
- set.each: This method is used to print the elements in the set. Whereas you cannot make changes in the set or in other words you cannot manipulate the set elements with the help of this method. We have got several set methods to manipulate the elements. This method will only print the elements in the forward direction.
- set.size(): This method tells the size of the set or the number of elements present in the set.
Variables used:
- vegetable: This is a set that contains the names of vegetables.
- i: This is working as a tracking variable which is telling the order of elements present in the set.
Code:
=begin
Ruby program to implement set.each method
=end
require 'set'
# Creation of new Set.
Vegetable = Set.new(["potato", "tomato","brinjal","onion"])
Vegetable.add("potato")
Vegetable.add("tomato")
Vegetable.add("Beetroot")
puts "Number of elements in set are #{Vegetable.size()}"
i = 1
Vegetable.each do |n|
puts "#{i} element is #{n}"
i = i + 1
end
Output
Number of elements in set are 5
1 element is potato
2 element is tomato
3 element is brinjal
4 element is onion
5 element is Beetroot
Explanation:
In the above code, first, we have created a set named Vegetable. We have made use of set.add() method to add more elements in the Vegetable set. Our objective is to print the elements present in the set. We can only do this with the help of the set.each method. It can also be considered as a loop that works on specific variables in Ruby. The variable ‘n’ is receiving the elements present in the set one by one. We have employed a variable i to print the order of the elements.
Ruby Set Programs »