红宝石镶嵌的优点
Set
的主要优点似乎是保留了独特的元素。但这可以在 Array
中轻松实现,
The main advantage of Set
seems to be maintaining unique elements. But that can be easily achieved in Array
with,
array = [2,3,4]
array | [2,5,6] # => [2,3,4,5,6]
唯一的独特功能(可能仅适用于少数用例)
The only distinct feature (which could apply to few use-cases) I came across was,
set1 = [1,2,3].to_set
set2 = [2,1,3].to_set
set1 == set2 # => true
[1,2,3] == [2,1,3] # => false
由于 Array
具有各种功能和操作与之相关联,何时以及为什么我应该使用 Set
?
Since Array
has various functions and operations associated with it, when and why should I use Set
?
有很多链接可以比较 Array
和 Set
但是我还没有遇到 Set
的重要应用。
There are many links that compare Array
and Set
but I haven't come across significant application of Set
.
当然,无论您使用 Set
做什么,都有一种使用 Array
的方法。使用 Set
的优点是,由于它是基于 Hash
实现的,因此对其的大多数操作都是O( 1)使用 Array
时的复杂度可以为O(n)。
Sure, whatever you can do with Set
, there is a way to do it with Array
. The advantage of using a Set
is that, since it is implemented based on Hash
, most operations on it are O(1) complexity, while doing it with Array
can be O(n).
示例为:
Set.new([1, 2, 3]).include?(2) # O(1) complexity
[1, 2, 3].include?(2) # O(n) complexity