Feature #17208
openAdd `Set#compact` and `Set#compact!` methods
Description
This is a proposal to add compact and compact! methods already owned by Array and Hash to Set.
-
Array#compactandArray#compact!has been around for a long time. -
Hash#compacthasHash#compact!been added since Ruby 2.4 ... https://bugs.ruby-lang.org/issues/11818 - There is
Setin collection libraries other thanArrayandHash. ButSetdoesn't havecompactandcompact!methods.
It behaves the same as compact and compact! methods of Array and Hash as follows.
Set#compact!:
# Removes all nil elements from self. Returns self if any elements removed, otherwise nil.
set = Set[1, 'c', nil] #=> #<Set: {1, "c", nil}>
set.compact! #=> #<Set: {1, "c"}>
set #=> #<Set: {1, "c"}>
set = Set[1, 'c'] #=> #<Set: {1, "c"}>
set.compact! #=> nil
set #=> #<Set: {1, "c"}>
Set#compact:
# Returns a new Set containing all non-nil elements from self.
set = Set[1, 'c', nil] #=> #<Set: {1, "c", nil}>
set.compact #=> #<Set: {1, "c"}>
set #=> #<Set: {1, "c", nil}>
set = Set[1, 'c'] #=> #<Set: {1, "c"}>
set.compact #=> #<Set: {1, "c"}>
set #=> #<Set: {1, "c"}>
Pull Request ... https://github.com/ruby/ruby/pull/3617
Updated by marcandre (Marc-Andre Lafortune) about 5 years ago
I second
Updated by shyouhei (Shyouhei Urabe) about 5 years ago
I like the feature, but isn't "Compact Set" a mathematical concept that refers to something different?
Updated by marcandre (Marc-Andre Lafortune) about 5 years ago
shyouhei (Shyouhei Urabe) wrote in #note-2:
I like the feature, but isn't "Compact Set" a mathematical concept that refers to something different?
It can, but the idea requires infinite sets, and all elements belonging to a topological space, I doubt many people would actually be confused.
Updated by bozhidar (Bozhidar Batsov) almost 5 years ago
I like the proposal. I also wonder if we shouldn't be able to able to reject nils at Set creation time, as nil rarely makes sense as a set value.
Updated by Eregon (Benoit Daloze) almost 5 years ago
bozhidar (Bozhidar Batsov) wrote in #note-4:
I like the proposal. I also wonder if we shouldn't be able to able to reject nils at Set creation time, as nil rarely makes sense as a set value.
With some option then?
I believe generic collections should accept any element, no special handling of nil or any other object.
(there might be additional requirements like #hash/#eql?, but any object can implement them)