Skip to content

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

class method

Set.new

[unchecked out A] (::_Each[A]) -> ::Set[A]
[unchecked out A, X] (::_Each[X]) { (X) -> A } -> ::Set[A]
[unchecked out A] (?nil) -> ::Set[A]
Set.new(object = nil) → new_set
Set.new(object = nil) {|element| ... } → new_set

Returns a new set based on the given object, which must be an Enumerable or nil.

With argument object given as nil, returns a new empty set:

Example
Set.new                          # => Set[]
Set.new { fail 'Cannot happen' } # => Set[]  # Block not called.

With no block given and enumerable argument object given, populates the new set with the elements of object:

Example
Set.new(%w[ a b c ])      # => Set["a", "b", "c"]
Set.new({foo: 0, bar: 1}) # => Set[[:foo, 0], [:bar, 1]]
Set.new(4..10)            # => Set[4, 5, 6, 7, 8, 9, 10]
Set.new(Dir.new('lib')).take(5)
# => [".", "..", "bundled_gems.rb", "bundler", "bundler.rb"]
Set.new(File.new('doc/NEWS/NEWS-4.0.0.md')).take(3)
# => ["# NEWS for Ruby 4.0.0\n", "\n", "This document is a list of user-visible feature changes\n"]

With a block given and enumerable argument object given, calls the block with each element of object; adds the block’s return value to the new set:

Example
Set.new(4..10) {|i| i * 2 } # => Set[8, 10, 12, 14, 16, 18, 20]

Related: see Methods for Creating a Set.

See also .[] #& #+ also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0