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#classify

[X] () { (A) -> X } -> ::Hash[X, self]
classify {|element| ... } → hash
classify → enumerator

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.

See also #add? #clear #add #collect! also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0