summaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
authorMarc-Andre Lafortune <github@marc-andre.ca>2020-10-01 23:55:46 -0400
committerHiroshi SHIBATA <hsbt@ruby-lang.org>2020-12-04 19:24:22 +0900
commit1804c3368cf4a94791fafa9701f79a2e6f76d5d8 (patch)
tree7d7020e913522676cb1070f242e6e50210395f22 /lib
parenta3db08d7b6ff119223f77e3df00b4f6deac971e2 (diff)
[ruby/set] Add `Set#<=>`
https://github.com/ruby/set/commit/447974a374
Diffstat (limited to 'lib')
-rw-r--r--lib/set.rb19
1 files changed, 16 insertions, 3 deletions
diff --git a/lib/set.rb b/lib/set.rb
index cb07037e82..625046d37c 100644
--- a/lib/set.rb
+++ b/lib/set.rb
@@ -45,9 +45,9 @@
# == Comparison
#
# The comparison operators <, >, <=, and >= are implemented as
-# shorthand for the {proper_,}{subset?,superset?} methods. However,
-# the <=> operator is intentionally left out because not every pair of
-# sets is comparable ({x, y} vs. {x, z} for example).
+# shorthand for the {proper_,}{subset?,superset?} methods.
+# The <=> operator reflects this order, or return `nil` for
+# sets that both have distinct elements ({x, y} vs. {x, z} for example).
#
# == Example
#
@@ -302,6 +302,19 @@ class Set
end
alias < proper_subset?
+ # Returns 0 if the set are equal,
+ # -1 / +1 if the set is a proper subset / superset of the given set,
+ # or nil if they both have unique elements.
+ def <=>(set)
+ return unless set.is_a?(Set)
+
+ case size <=> set.size
+ when -1 then -1 if proper_subset?(set)
+ when +1 then +1 if proper_superset?(set)
+ else 0 if self.==(set)
+ end
+ end
+
# Returns true if the set and the given set have at least one
# element in common.
#