Skip to main content

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 {
        # Display object value  
        print("  ",x)  

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

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

# Display set values
puts "Set A"
puts "Set B"
puts "Set C"
puts "Set 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 =['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