Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

empty
set
ruby
communitycreator

What is set.empty?() 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.

Overview

In Ruby, we can check whether a set is empty or not by using the empty?() method. In Ruby, a set is a collection of unordered, unique and non-duplicated elements. Sometimes a set can become empty, and here is when the empty?() method comes in handy.

Syntax

set.empty?()

Parameters

set: This is the set that we want to check for emptiness.

Return value

The value returned is a boolean. If the set is empty, then true is returned. Otherwise, false is returned.

Example

# require the set class
require "set"
# create some sets
EvenNumbers = Set.new([2, 4, 6, 8, 10])
NumbersToTen = Set.new([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
Workers = Set.new(["Amaka", "Chioma", "Titi"])
EmptySet = Set.new([])
# clear a particular set
NumbersToTen.clear
# check if sets are empty
puts EvenNumbers.empty?() # false
puts NumbersToTen.empty?() # true
puts Workers.empty?() # false
puts EmptySet.empty?() # true
Check if a Set is empty in Ruby

Explanation

  • Line 2: We require the set class.
  • Lines 5–8: We created some set instances, one of which is an empty set.
  • Line 11: We use the clear method to clear or empty the NumbersToTen set.
  • Lines 14–17: Using the empty?() method, we check each set to determine whether it is empty or not. We print the corresponding results to the console.

RELATED TAGS

empty
set
ruby
communitycreator

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.

Keep Exploring