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

Categories

0 votes
972 views
in Technique[技术] by (71.8m points)

arrays - Advantages of Set in ruby

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

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

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...