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 it
require "set"
# create sets
Languages = Set.new(["Ruby", "PHP","JavaScript","Python"])
Numbers = Set.new
Numbers << 1
Numbers << 2
Numbers << 3
Techgiants = Set.new(["Google"])
Techgiants.add("Netflix")
Techgiants.add("Apple")
Techgiants.add("Amazon")
Techgiants.add("Meta")
Emptyset = Set.new
# print size
puts Languages.size
puts Numbers.size
puts Techgiants.size
puts Emptyset.size

Explanation

  • Line 2: We require the set class.
  • Lines 5–17: We create different sets.
  • Lines 20–23: We obtain the sizes of the sets using the size method. We then print the results to the console.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources