Ruby Set 相交?方法
intersect?(Set) 方法是 Ruby 庫中預定義的方法。您可以將此方法稱為與 Set.disjoint?() 方法完全相反的方法。借助這種方法,我們可以檢查這兩個集合是否具有任何公共元素。如果我們比較的集合有任何共同元素,那麽隻有當兩個集合中沒有共同元素時,該方法才會返回真和假。在使用 Ruby 編程時,此方法可為您提供各種優勢。讓我們看一下它的語法和示例,以便更好地理解這個方法是如何在 Ruby 代碼中實現的。
用法:
Set.intersect?(Set)
範例1:
=begin
Ruby program to demonstrate the implementation of
intersect?() method.
=end
require 'set'
Vegetable=Set.new(["potato", "brocolli","broccoflower","lentils","peas","fennel","chilli","cabbage"])
Fruits = Set.new(["Apple","Mango","Banana","Orange","Grapes"])
p = Vegetable.intersect?(Fruits)
if p == false
puts "There is no common element exists between both the sets."
else
puts "The sets are having common elements."
end
輸出
There is no common element exists between both the sets.
說明:
在上麵的代碼中,我們聲明了兩個 Set 類的實例,稱為Vegetable
和Fruits
.我們想檢查兩個集合之間是否存在一些公共元素。我們是在相交的幫助下進行的嗎?方法。我們知道它返回一個布爾值。所以,我們將它的值存儲在一個變量中。然後我們檢查該變量的值,如果它是假的,那麽它隻是意味著兩個集合之間沒有共同的元素。即使 Set 類的兩個實例之間隻有一個元素是通用的,此方法也會為您提供結果為真。
範例2:
=begin
Ruby program to show the implementation of intersect?() .
=end
require 'set'
p = Set[2,3,5].intersect?Set[2,56,4,3,22,66,34]
if p == false
puts "There is no common element exists between both the sets."
else
puts "The sets are having common elements."
end
輸出
The sets are having common elements.
說明:
在上麵的代碼中,我們是在調用intersect的時候創建集合?函數。函數 intersect?() 正在檢查兩個集合是否有一些共同的元素。如果集合甚至有一個公共元素,那麽它將返回 true。我們將其返回值存儲在變量“p”中。我們正在檢查 p 的值,如果它是假的,那麽這意味著兩個集合中有一些共同的元素。我們在 puts 語句的幫助下通知用戶這一點。
相關用法
- Ruby Set intersect?()用法及代碼示例
- Ruby Set intersection()用法及代碼示例
- Ruby Set include?()用法及代碼示例
- Ruby Set flatten()用法及代碼示例
- Ruby Set compare_by_identity?用法及代碼示例
- Ruby Set size()用法及代碼示例
- Ruby Set member?()用法及代碼示例
- Ruby Set compare_by_identity()用法及代碼示例
- Ruby Set divide()用法及代碼示例
- Ruby Set replace()用法及代碼示例
- Ruby Set subtract()用法及代碼示例
- Ruby Set proper_subset?()用法及代碼示例
- Ruby Set difference()用法及代碼示例
- Ruby Set clear()用法及代碼示例
- Ruby Set length()用法及代碼示例
- Ruby Set empty?()用法及代碼示例
- Ruby Set superset?用法及代碼示例
- Ruby Set add()用法及代碼示例
- Ruby Set delete()用法及代碼示例
- Ruby Set delete?用法及代碼示例
注:本文由純淨天空篩選整理自 Ruby Set intersect? Method with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。