Q:

Find the difference between two sets in Ruby

belongs to collection: Ruby Set Programs

0

Finding differences simply means that finding elements that are uncommon between two sets as well as are only present in the first set. We can find this, with the help of a – operator. You can also consider the objective as to find the unique elements from the first set or you can say that the set which is passed as the first argument.

Methods used:

    • -: In ruby, most of the operators are considered as methods. This operator or method is used to find out the unique elements from the set which is provided as the first argument to the - method. The return type of this operator is a set itself.

Syntax:

    SetA - SetB
  • set.eachset.each method is used to print the elements from the set one by one. It will provide you elements in the forward direction.

Variables used:

  • Vegetable: It is a set. It is the first argument passed as the argument in & operator.
  • Sabzi: It is an instance of Set class. It is the second argument that is passed in & operator.
  • New_set: It is containing the set which is returned from the & operator or method.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Code:

=begin
Ruby program to show implementation of - operator
=end

require 'set'

Vegetable=Set.new(["potato","broccolli","broccoflower","lentils","peas","fennel","chilli","cabbage"])

Sabzi=Set.new(["potato","tomato","brinjal","onion","beetroot","capsisum","chilli"])

New_set = Vegetable - Sabzi

New_set.each do |string|
	puts "#{string} element from new set"
end

Output

broccoli element from new set
broccoflower element from new set
lentils element from new set
peas element from new set
fennel element from new set
cabbage element from new set

Explanation:

In the above code, it is shown how one can find the unique elements from the first set by finding the difference from both the sets. As you can see above, we have defined three sets, two sets are for carrying out the processing and one set is for storing the common elements from both the sets. We have taken help from the set.each method to print all the elements from the new set. As a result, you can find that the new set contains all the elements which are not present in the second set. This method would not give you elements that are unique in the second set.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Merge two sets in Ruby... >>
<< Find the common elements from two sets in Ruby...