Join all the elements of two sets in Ruby

Joining elements of two sets: Here, we are going to learn how to join all the elements of two sets in Ruby programming language?
Submitted by Hrithik Chandra Prasad, on October 11, 2019

In this program, we will see how we can combine the two sets? This is not a very difficult task. This can be easily done with the help of the + operator. In many places of programming, you will find that + operator is overloaded for various types to meet various purposes. Here in the case of sets, + operator works likes arithmetic OR. It combines all the elements from both the sets and returns a set that contains all those elements. Let us look at the code and understand how we can complete this task.

Methods used:

  1. + : In ruby, most of the operators are considered as methods. This operator or method is used to combine two sets provided as arguments to the method. The return type of this operator is set itself. The set returned is having all the elements which are present in both the sets. Syntax:
        SetA + SetB
    
  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 an instance of Set class. 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.

Program:

=begin
Ruby program to show implementation of + operator
=end
require 'set'

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

Sabzi=Set.new(["potato","tomato","brinjal","onion","beetroot","capsicum","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
peas element from new set
beetroot element from new set
chilli element from new set
cabbage element from new set
capsicum element from new set

Explanation:

In the above code, it is shown how one can combine all the elements 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 observe that there is no repetition of elements. It is having all the elements and each element is present only for one time. Elements are appearing single even if they are present in both sets.

Ruby Set Programs »




Comments and Discussions!

Load comments ↻





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