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
set.c
View on GitHub ↗
static VALUE
set_i_initialize(int argc, VALUE *argv, VALUE set)
{
if (RBASIC(set)->flags & RSET_INITIALIZED) {
rb_raise(rb_eRuntimeError, "cannot reinitialize set");
}
RBASIC(set)->flags |= RSET_INITIALIZED;
VALUE other;
rb_check_arity(argc, 0, 1);
if (argc > 0 && (other = argv[0]) != Qnil) {
if (RB_TYPE_P(other, T_ARRAY)) {
rb_len_t i;
int block_given = rb_block_given_p();
set_table *into = RSET_TABLE(set);
for (i=0; i<RARRAY_LEN(other); i++) {
VALUE key = RARRAY_AREF(other, i);
if (block_given) key = rb_yield(key);
set_table_insert_wb(into, set, key);
}
}
else {
rb_block_call(other, enum_method_id(other), 0, 0,
rb_block_given_p() ? set_initialize_with_block : set_initialize_without_block,
set);
}
}
return 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.