Michael Durrant
Michael Durrant

Reputation: 96504

ruby - how to created SortedSet from Set?

If I have an array I can create a set (unique values) from it with

require 'set'
s = [11,12,3,2,3,4,3,5,89,1,2,3,4]
uniq_s = s.to_set # gives [11,12,3,2,4,5,89,1]

If I want the result to be sorted I could do this with sorted_s = s.sort

How could I also do this using a SortedSet ? I tried using array.to_sorted_set but that doesn't exist

Upvotes: 1

Views: 586

Answers (2)

3limin4t0r
3limin4t0r

Reputation: 21130

You can also pass the set class as described in the #to_set documentation.

require 'set'
s = [11,12,3,2,3,4,3,5,89,1,2,3,4]
s.to_set(SortedSet)
#=> #<SortedSet: {1, 2, 3, 4, 5, 11, 12, 89}>

Upvotes: 5

Michael Durrant
Michael Durrant

Reputation: 96504

Pass the existing set to SortedSet.new

Example:

irb(main):046:0> s = [11,12,3,2,3,4,3,5,89,1,2,3,4].to_set
=> #<Set: {11, 12, 3, 2, 4, 5, 89, 1}>
irb(main):047:0> sorted_s = SortedSet.new(s)
=> #<SortedSet: {1, 2, 3, 4, 5, 11, 12, 89}>
irb(main):048:0> 

Upvotes: 5

Related Questions