What is set.length in Ruby?

Overview

A set in Ruby is a data structure used to store unique elements. In Ruby, the length of a set is the number of elements a set contains. We use the predefined method length to determine the size of the set. It was created solely for this purpose.

Syntax

Set.length
Syntax for the length method of a set in Ruby

Return value

The value returned is an integer. This integer represents the number of elements present in a set.

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
Emptyset = Set.new
# print length
puts Languages.length
puts Numbers.length
puts Emptyset.length

Explanation

  • line 2: We used the required set class
  • line 5–11: We create sets (languages, Numbers, Emptyset)
  • line 14–16: We calculate the lengths of sets and then print them on the console.
  • Free Resources