mirror of
https://github.com/ruby/ruby.git
synced 2022-11-09 12:17:21 -05:00
parent
a3db08d7b6
commit
1804c3368c
2 changed files with 34 additions and 3 deletions
19
lib/set.rb
19
lib/set.rb
|
@ -45,9 +45,9 @@
|
||||||
# == Comparison
|
# == Comparison
|
||||||
#
|
#
|
||||||
# The comparison operators <, >, <=, and >= are implemented as
|
# The comparison operators <, >, <=, and >= are implemented as
|
||||||
# shorthand for the {proper_,}{subset?,superset?} methods. However,
|
# shorthand for the {proper_,}{subset?,superset?} methods.
|
||||||
# the <=> operator is intentionally left out because not every pair of
|
# The <=> operator reflects this order, or return `nil` for
|
||||||
# sets is comparable ({x, y} vs. {x, z} for example).
|
# sets that both have distinct elements ({x, y} vs. {x, z} for example).
|
||||||
#
|
#
|
||||||
# == Example
|
# == Example
|
||||||
#
|
#
|
||||||
|
@ -302,6 +302,19 @@ class Set
|
||||||
end
|
end
|
||||||
alias < proper_subset?
|
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
|
# Returns true if the set and the given set have at least one
|
||||||
# element in common.
|
# element in common.
|
||||||
#
|
#
|
||||||
|
|
|
@ -332,6 +332,24 @@ class TC_Set < Test::Unit::TestCase
|
||||||
}
|
}
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def test_spacecraft_operator
|
||||||
|
set = Set[1,2,3]
|
||||||
|
|
||||||
|
assert_nil(set <=> 2)
|
||||||
|
|
||||||
|
assert_nil(set <=> set.to_a)
|
||||||
|
|
||||||
|
[Set, Set2].each { |klass|
|
||||||
|
assert_equal(-1, set <=> klass[1,2,3,4], klass.name)
|
||||||
|
assert_equal( 0, set <=> klass[3,2,1] , klass.name)
|
||||||
|
assert_equal(nil, set <=> klass[1,2,4] , klass.name)
|
||||||
|
assert_equal(+1, set <=> klass[2,3] , klass.name)
|
||||||
|
assert_equal(+1, set <=> klass[] , klass.name)
|
||||||
|
|
||||||
|
assert_equal(0, Set[] <=> klass[], klass.name)
|
||||||
|
}
|
||||||
|
end
|
||||||
|
|
||||||
def assert_intersect(expected, set, other)
|
def assert_intersect(expected, set, other)
|
||||||
case expected
|
case expected
|
||||||
when true
|
when true
|
||||||
|
|
Loading…
Reference in a new issue