Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

set
delete
ruby
communitycreator

What is the set.delete_if() method 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

The delete() method is used to delete an element in a set. To delete a couple of elements that meet a particular condition, we must use the delete_if() condition. If the block of an element returns true, the element is deleted. The block here takes each element as it loops the set, and if the element satisfies its condition, it is removed.

Syntax

set.delete_if(condition)
Syntax for delete_if() method

Parameters

condition: This is the block condition that is specified for each element.

Return value

It returns a new set with some of its elements deleted.

Example

# require the set class
require "set"
# create a set
RandomNumbers = Set.new([1, 4, 29, 12, 30, 66, 72])
puts "Previous Elements:"
puts RandomNumbers.to_a
# delete elements that are even Numbers
RandomNumbers.delete_if{|num| num % 2 == 0}
puts "\nElements remaining:"
puts RandomNumbers.to_a
Remove some elements in a set using delete_if() method

Explanation

  • Line 2We use require to obtain a set class.
  • Line 5: We create a set of random numbers and call it RandomNumbers
  • Line 8: We use the to_a method to print the set to the console as an array.
  • Line 12: We delete even-numbered elements by specifying if they can be divided by two without a remainder.
  • Line 15: We print the set again with the deleted elements that satisfy the above condition.

RELATED TAGS

set
delete
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