Ruby Set delete method

In ruby programming language, delete() set method are use to remove given object in an set. And returns the reference of self set. Syntax of this method as follows.

set.delete(obj)  -> self
set.delete?(obj) -> self or nil

This method take a parameter value which is indicating the whose object is to remove from the given set. There is two variants of delete method in set. such as delete() and delete?().

delete() method always returning self. and delete?() method return self when delete object exists in set. Otherwise returning a nil.

Set delete method example

In this section mentioning few examples to understand delete() method functionality in ruby Set.

# Example 1
require "set"

# New set
record = Set[10,["a","b"], true, [1,2], 20]
# Before delete 
print("Before record : ",record.to_a)

# delete object
s = record.delete(["a","b"]);

# After delete 
print("\nAfter record  : " ,record.to_a)
print("\n            s : ", s.to_a)
Ruby set delete method example 1
Before record : [10, ["a", "b"], true, [1, 2], 20]
After record  : [10, true, [1, 2], 20]
            s : [10, true, [1, 2], 20]
# Example 2
require "set"

# New set
record = Set[10,["a","b"], true, [1,2], 20]
# Before delete 
print("Before record : ",record.to_a)

# delete object
s1 = record.delete?(["a"]) # nil 
s2 = record.delete?([1,2]) 

# After delete 
print("\nAfter record  : " ,record.to_a)
print("\n           s1 : ", s1.to_a)
print("\n           s2 : ", s2.to_a)
Ruby set delete method example 2
Before record : [10, ["a", "b"], true, [1, 2], 20]
After record  : [10, ["a", "b"], true, 20]
           s1 : []
           s2 : [10, ["a", "b"], true, 20]


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved