ruby 集合 分組
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.
- :在Ruby中,大多數運算符被視為方法。 此運算符或方法用于從集合中查找唯一元素,該元素作為-方法的第一個參數提供。 此運算符的返回類型本身就是集合。
- 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.
set.each : set.each方法用于逐個打印集合中的元素。 它將為您提供前進方向的元素。
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.
Sabzi :它是Set類的實例。 這是在&運算符中傳遞的第二個參數。
New_set: It is containing the set which is returned from the & operator or method.
New_set :它包含從&運算符或方法返回的集合。
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.
在上面的代碼中,顯示了如何通過查找兩個集合之間的差異來從第一個集合中找到唯一元素 。 如上所示,我們定義了三個集合,兩個集合用于執行處理,一個集合用于存儲兩個集合中的公共元素。 我們從set.each方法獲得幫助,以打印新集中的所有元素。 結果,您會發現新集合包含第二個集合中不存在的所有元素。 此方法不會為您提供第二組中唯一的元素。
翻譯自: https://www.includehelp.com/ruby/find-the-difference-between-two-sets.aspx
ruby 集合 分組