SortedSet

424 views

What is the return value of the following Ruby code?

require 'set'

tags = SortedSet.new

tags << :ruby
tags << :algol
tags << :lua
tags << :ruby

tags.to_a # => ???

The correct answer is

[:ruby, :algol, :lua, :ruby]

It raises DuplicatesError

[:algol, :lua, :ruby]

[:ruby, :algol, :lua]

Unlock Your Ruby Potential

Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!

Explanation

The SortedSet class allows you to create an ascending collection of unique sorted values.

When requiring the 'set' Standard Library (and if the sorted_set gem has been installed) the SortedSet class will be automatically available.

Indeed, this class has been extracted into a gem and this gem is currently maintained by Akinori Musha who is a trusted Ruby committer.

To go further!

Join the RubyCademy community to master the intricacies of this lesser-known library! You'll also gain access to hundreds of other PRO tips! 🤩

💚

Unlock Your Ruby Potential

Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!

RubyCademy ©