Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

instance method

Range#to_set

() -> ::Set[E]
[T] () { (E) -> T } -> ::Set[T]
to_set → set

Returns a set containing the elements in self, if a finite collection; raises an exception otherwise.

Example
(1..4).to_set   # => Set[1, 2, 3, 4]
(1...4).to_set   # => Set[1, 2, 3]

(1..).to_set
# in 'Range#to_set': cannot convert endless range to a set (RangeError)

Ruby version changes

  1. 4.1
  2. 4.0
See also #to_s #to_a also in 4.0