Find the common elements from two sets in Ruby

Finding the common elements from two sets: Here, we are going to learn how to find the common elements from two sets in Ruby programming language?
Submitted by Hrithik Chandra Prasad, on October 11, 2019

Ruby is very rich in the library. It has various methods for meeting specific functionalities. In Ruby, operators are basically methods with two arguments generally. We have gone through the description of sets in Ruby. We have seen their implementation also. In sets, & operator works similarly to arithmetic and you can say that it takes two sets as arguments and finds the common elements or the repeated elements from both the sets. The return type of this method is a set and that set contains all the elements which are common in both the sets.

Methods used:

  1. & : In ruby, most of the operators are considered as methods. This operator or method is used to find out the common elements from the sets provided as arguments to the method. The return type of this operator is set itself.
  2. 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 which is passed in & operator.
  • New_set : It is containing the set which is returned from the & operator or method.

Program:

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

require 'set'

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

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

potato element from new set
tomato element from new set
brinjal element from new set
onion element from new set
beetroot element from new set
chilli element from new set

Explanation:

In the above code, it is shown how one can find the common elements from both 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 common in both the sets.

Ruby Set Programs »




Comments and Discussions!

Load comments ↻





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