What is the set.reject!() method in Ruby?

Overview

The reject!() method of a set is used in Ruby to delete some elements that return true for a specified condition. It requires a block that sets the condition for each element of the set.

If the element meets the specified condition in the block, then the element is deleted. If no element meets the condition, then nothing is returned.

Syntax

set.reject!{|e| condition}
The syntax for reject!() method in Ruby

Parameters

  • e: This represents each element of the set.
  • condition: This is the condition specified.

Return value

The value returned is a modified set from which elements or values that meet the specified condition are deleted. If no element matches the condition, then nothing is removed.

Code 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])
Names = Set.new(["Ade", "James", "Amaka", "Titi"])
# delete some elements
EvenNumbers.reject!{|e| e > 4}
NumbersToTen.reject!{|e| e % 2 != 0}
Names.reject!{|e| e.length > 4}
# print modified sets as arrays
puts "#{EvenNumbers.to_a}"
puts "#{NumbersToTen.to_a}"
puts "#{Names.to_a}"

Explanation

  • Line 2: We require the set class.
  • Lines 5–7: We create some sets.
  • Lines 10–12: We call the reject!() method to delete the elements from the sets created in lines 5–7. In line 10, we reject the numbers greater than 4. In line 11, we reject the odd numbers. In line 12, we reject the names that are longer than four letters in length.
  • Lines 15–17: We print the modified sets as arrays.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources