Skip to content

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

instance method

Set#to_set

() -> ::Set[A]
[T] () { (A) -> T } -> ::Set[T]
to_set {|element| ... } → new_set
to_set → self or new_set

With a block given, creates and returns a new set; calls the block with each element of self, and adds the block’s returns value to the new set:

Example
set = Set[*0..9]        # => Set[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
set.to_set {|i| i * 2 } # => Set[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

With no block given, when self is an instance of Set, returns self:

Example
set = Set[*0..9]
set.to_set
set.to_set.equal?(set) # => true

With no block given, when self is an instance of a subclass of Set, returns a set containing the elements of self:

Example
class MySet < Set; end
my_set = MySet[*0..9] # => #<MySet: {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}>
set = my_set.to_set   # => Set[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Related: see Methods for Converting.

Ruby version changes

  1. 4.1
  2. 4.0
See also #to_s #union #to_a also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0