Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
set
length

What is set.length in Ruby?

okwudili onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code

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

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.
  • RELATED TAGS

    ruby
    set
    length

    Grokking Modern System Design Interview for Engineers & Managers

    Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

    Answers Code
    Keep Exploring