Ruby Set add() method

In ruby programming, add() set method are used to add unique element in given set. When element is not exist in set this method put given element and returns the reference of updated self set.

add(obj)  -> self
add?(obj) -> self or nil

This method are takes single parameter. There is two variants of this method, One is add() that is simple which is always returning the reference of given set. And add?() method is adding a new object when if object is not present and returning a self set reference. But the other case when the set element already exists it returns a nil value.

Set add method example

Here include few example to understand add() method functionality in ruby language.

 # Example 1
require "set"

# Display set element
def printSet(record)
    # iterating the set element
    record.each {
        # Display object value  
        print("  ",x)  

# New set 
record = Set[10,20]

# Add new value
data = record.add(15)

# Display set
10  20  15
Ruby set add method example 1

In above example set are initial 2 value and after that added a value 15. Note that this method are return the self.

# Example 2
require "set"

# New set
record = Set[10, 20]

# Define an array
value = [true, 15, false]

# Add an array
s1 = record.add?(value)

# When adding an object which already exists
s2 = record.add?(10) # nil

# Display set
print("\n", s1.to_a)
print("\n", s2.to_a)
[10, 20, [true, 15, false]]
[10, 20, [true, 15, false]]
Ruby set add method example 2

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,, All rights reserved