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.
set.reject!{|e| condition}
e
: This represents each element of the set.condition
: This is the condition specified.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.
# require the set classrequire "set"# create some setsEvenNumbers = 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 elementsEvenNumbers.reject!{|e| e > 4}NumbersToTen.reject!{|e| e % 2 != 0}Names.reject!{|e| e.length > 4}# print modified sets as arraysputs "#{EvenNumbers.to_a}"puts "#{NumbersToTen.to_a}"puts "#{Names.to_a}"
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.