本文簡要介紹ruby語言中 Set類
的用法。
這個庫提供了 Set
類,它處理無重複的無序值的集合。它是 Array 的直觀 inter-operation 設施和 Hash 的快速查找的混合體。
為方便起見,將方法to_set
添加到 Enumerable
。
Set
實現無重複值的無序值集合。這是 Array 的直觀 inter-operation 設施和 Hash 的快速查找的混合體。
Set
易於與 Enumerable
對象一起使用(實現 each
)。除了集合和數組之外,大多數初始化方法和二元運算符都接受通用 Enumerable
對象。可以使用to_set
方法將 Enumerable
對象轉換為 Set
。
-
元素的相等性根據
Object#eql?
和Object#hash
確定。使用Set#compare_by_identity
使集合按其身份比較其元素。 -
Set
假設每個元素的標識在存儲時不會改變。修改集合中的元素會使集合處於不可靠狀態。 -
當要存儲字符串時,將存儲該字符串的凍結副本,除非原始字符串已被凍結。
比較
比較運算符 <
、 >
、 <=
和 >=
被實現為 {proper_,}{subset?,superset?} 方法的簡寫。 <=>
運算符反映了這個順序,或者為都具有不同元素的集合返回 nil
(例如 {x, y}
與 {x, z}
)。
示例
require 'set'
s1 = Set[1, 2] #=> #<Set: {1, 2}>
s2 = [1, 2].to_set #=> #<Set: {1, 2}>
s1 == s2 #=> true
s1.add("foo") #=> #<Set: {1, 2, "foo"}>
s1.merge([2, 6]) #=> #<Set: {1, 2, "foo", 6}>
s1.subset?(s2) #=> false
s2.subset?(s1) #=> true
接觸
-
Akinori MUSHA <knu@iDaemons.org>(當前維護者)
相關用法
- Ruby Set flatten()用法及代碼示例
- Ruby Set.replace用法及代碼示例
- Ruby Set intersection()用法及代碼示例
- Ruby Set.==用法及代碼示例
- Ruby Set.disjoint?用法及代碼示例
- Ruby Set size()用法及代碼示例
- Ruby Set compare_by_identity?用法及代碼示例
- Ruby Set merge()用法及代碼示例
- Ruby Set.classify用法及代碼示例
- Ruby Set add?用法及代碼示例
- Ruby Set compare_by_identity()用法及代碼示例
- Ruby Set flatten!()用法及代碼示例
- Ruby Set divide()用法及代碼示例
- Ruby Set replace()用法及代碼示例
- Ruby Set.[]用法及代碼示例
- Ruby Set.===用法及代碼示例
- Ruby Set include?()用法及代碼示例
- Ruby Set subtract()用法及代碼示例
- Ruby Set member?()用法及代碼示例
- Ruby Set intersect?()用法及代碼示例
- Ruby Set proper_subset?()用法及代碼示例
- Ruby Set difference()用法及代碼示例
- Ruby Set.-用法及代碼示例
- Ruby Set.to_a用法及代碼示例
- Ruby Set.add?用法及代碼示例
注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 Set類。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。