Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

set
ruby
size
communitycreator

How to get the size of a set in Ruby

okwudili onyejiaku

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
Get the size of a set in Ruby

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.

RELATED TAGS

set
ruby
size
communitycreator
RELATED COURSES

View all Courses

Keep Exploring