Ruby Set difference function

The ruby difference function is applied to the set and this function takes a parameter (enumerable objects). This function duplicates the implemented set and extracts its objects by the given parameter object that is the same in the parameter. And returns a new resultant set. for example.

# Ruby set difference example
require "set"

# Display set element
def printSet(record)
    record.each {
        |x|
        # Display object value  
        print("  ",x)  
    }
    print("\n")
end

# Given set a,b
a = Set.new(['a','z' ,'p' ,'i'])
b = Set.new(['c','i','l','a'])

# Calculate difference
c = a.difference(b)
d = b.difference(a)

# Display set values
puts "Set A"
printSet(a)
puts "Set B"
printSet(b)
puts "Set C"
printSet(c)
puts "Set D"
printSet(d)
Ruby set difference function example
Set A
  a  z  p  i
Set B
  c  i  l  a
Set C
  z  p
Set D
  c  l

Parameter type must be an enumerable type such as array, set etc. Let see other example.

# Ruby set difference example B
require "set"

a = Set.new(['a','z' ,'p' ,'i'])

# Calculate difference
b = a.difference(['p',1,2])
c = a.difference(a)

# Display set values
print("Set A",a.to_a)   # Set A["a", "z", "p", "i"]
print("\nSet B",b.to_a) # Set B["a", "z", "i"]
print("\nSet C",c.to_a) # Set C[]
Ruby set difference function example b
Set A["a", "z", "p", "i"]
Set B["a", "z", "i"]
Set C[]


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