Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

Since Array has various functions and operations associated with it, when and why should I use Set?

There are many links that compare Array and Set but I haven't come across significant application of Set.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
912 views
Welcome To Ask or Share your Answers For Others

1 Answer

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).

Examples are:

Set.new([1, 2, 3]).include?(2) # O(1) complexity
[1, 2, 3].include?(2) # O(n) complexity

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...