Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
instance method
Set#divide
() { (A, A) -> ::Hash::_Key } -> ::Set[self]
() { (A) -> ::Hash::_Key } -> ::Set[self]
divide {|ele| ... } → new_set
divide {|ele0, ele1| ... } → new_set
divide → enumerator
set.c
View on GitHub ↗
static VALUE
set_i_divide(VALUE set)
{
RETURN_SIZED_ENUMERATOR(set, 0, 0, set_enum_size);
if (rb_block_arity() == 2) {
return set_divide_arity2(set);
}
VALUE values = rb_hash_values(set_i_classify(set));
set = set_alloc_with_size(rb_cSet, RARRAY_LEN(values));
set_merge_enum_into(set, values);
return set;
}
With a block given, returns a set of sets.
For a block that accepts one argument, calls the block with each element; creates a set for each distinct block return value:
Example
set = Set[*0..9] # => Set[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # Divide into mod 3 sets. set.divide {|ele| ele % 3 } # => Set[Set[0, 3, 6, 9], Set[1, 4, 7], Set[2, 5, 8]] # Divide into mod 5 sets. set.divide {|ele| ele % 5 } # => Set[Set[0, 5], Set[1, 6], Set[2, 7], Set[3, 8], Set[4, 9]] Set[0].divide {|ele| anything } # => Set[Set[0]] Set[].divide {|ele| not called } # => Set[]
For a block that accepts two arguments, divides self into connected components based on the binary relation defined by the block, calling the block with each 2-element permutation of the elements of self:
Example
set = Set[*0..9] # => Set[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # Divide into mod 2 sets. set.divide {|i, j| (i - j) % 2 == 0 } # => Set[Set[0, 2, 4, 6, 8], Set[1, 3, 5, 7, 9]] # Divide into mod 3 sets. set.divide {|i, j| (i - j) % 3 == 0 } # => Set[Set[0, 3, 6, 9], Set[1, 4, 7], Set[2, 5, 8]] Set[0].divide {|i, j| not called } # => Set[Set[0]] Set[].divide {|i, j| not called } # => Set[]
With no block given, returns an Enumerator.
Related: see Methods for Converting.