What is the set.delete_if() method in Ruby?
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)
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 classrequire "set"# create a setRandomNumbers = Set.new([1, 4, 29, 12, 30, 66, 72])puts "Previous Elements:"puts RandomNumbers.to_a# delete elements that are even NumbersRandomNumbers.delete_if{|num| num % 2 == 0}puts "\nElements remaining:"puts RandomNumbers.to_a
Explanation
- Line 2: We use
requireto obtain asetclass.
- Line 5: We create a set of random numbers and call it
RandomNumbers.
- Line 8: We use the
to_amethod 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.