×

Ruby Tutorial

Ruby Basics

Ruby Control Statements

Ruby Methods

Ruby Classes and Methods

Ruby Arrays

Ruby Sets

Ruby Strings

Ruby Classes & Objects

Ruby Hash

Ruby Tools

Ruby Functions

Ruby Built-in Functions

Misc.

Ruby Programs

Find the difference between two sets in Ruby

By IncludeHelp Last updated : December 01, 2024

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 to find difference between two sets

  • -: 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.each: set.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.

Ruby program to find difference between two sets

=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.

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.