Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
instance method
Set#classify
[X] () { (A) -> X } -> ::Hash[X, self]
classify {|element| ... } → hash
classify → enumerator
set.c
View on GitHub ↗
static VALUE
set_i_classify(VALUE set)
{
RETURN_SIZED_ENUMERATOR(set, 0, 0, set_enum_size);
VALUE args[3];
args[0] = rb_hash_new();
args[1] = rb_obj_class(set);
args[2] = RBOOL(RSET_COMPARE_BY_IDENTITY(set));
set_iter(set, set_classify_i, (st_data_t)args);
return args[0];
}
With a block given, calls the block with each element of self; returns a hash whose keys are the block’s return values. The value for each key is a set containing the elements for which the block returned that key.
This example classifies elements by their classes:
Example
set = Set[*(5..7), *%w[foo bar]] # => Set[5, 6, 7, "foo", "bar"] set.classify {|element| element.class } # => {Integer => Set[5, 6, 7], String => Set["foo", "bar"]}
With no block given, returns an Enumerator.
Related: see Methods for Converting.