How to get the size of a set in Ruby
Overview
A set is a data structure containing unique elements. The size of a set is the number of elements that are added to the set. It returns an integer representing the count of elements present in the set.
To get this size, we can use the size method.
Syntax
Set.size
Syntax for a size of set
Parameters
None.
Return value
An integer is returned. This integer represents the number of elements present in the set.
Code example
# require the set Class to use itrequire "set"# create setsLanguages = Set.new(["Ruby", "PHP","JavaScript","Python"])Numbers = Set.newNumbers << 1Numbers << 2Numbers << 3Techgiants = Set.new(["Google"])Techgiants.add("Netflix")Techgiants.add("Apple")Techgiants.add("Amazon")Techgiants.add("Meta")Emptyset = Set.new# print sizeputs Languages.sizeputs Numbers.sizeputs Techgiants.sizeputs Emptyset.size
Explanation
- Line 2: We require the
setclass. - Lines 5β17: We create different sets.
- Lines 20β23: We obtain the sizes of the sets using the
sizemethod. We then print the results to the console.