Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 17 additions & 7 deletions lib/set.rb
Original file line number Diff line number Diff line change
Expand Up @@ -468,25 +468,35 @@ def <=>(set)
end
end

# Returns true if the set and the given set have at least one
# Returns true if the set and the given enumerable have at least one
# element in common.
#
# Set[1, 2, 3].intersect? Set[4, 5] #=> false
# Set[1, 2, 3].intersect? Set[3, 4] #=> true
# Set[1, 2, 3].intersect? 4..5 #=> false
# Set[1, 2, 3].intersect? [3, 4] #=> true
def intersect?(set)
set.is_a?(Set) or raise ArgumentError, "value must be a set"
if size < set.size
any? { |o| set.include?(o) }
else
case set
when Set
if size < set.size
any? { |o| set.include?(o) }
else
set.any? { |o| include?(o) }
end
when Enumerable
set.any? { |o| include?(o) }
else
raise ArgumentError, "value must be enumerable"
end
end

# Returns true if the set and the given set have no element in
# common. This method is the opposite of `intersect?`.
# Returns true if the set and the given enumerable have
# no element in common. This method is the opposite of `intersect?`.
#
# Set[1, 2, 3].disjoint? Set[3, 4] #=> false
# Set[1, 2, 3].disjoint? Set[4, 5] #=> true
# Set[1, 2, 3].disjoint? [3, 4] #=> false
# Set[1, 2, 3].disjoint? 4..5 #=> true
def disjoint?(set)
!intersect?(set)
end
Expand Down
6 changes: 5 additions & 1 deletion test/test_set.rb
Original file line number Diff line number Diff line change
Expand Up @@ -354,13 +354,17 @@ def assert_intersect(expected, set, other)
case expected
when true
assert_send([set, :intersect?, other])
assert_send([set, :intersect?, other.to_a])
assert_send([other, :intersect?, set])
assert_not_send([set, :disjoint?, other])
assert_not_send([set, :disjoint?, other.to_a])
assert_not_send([other, :disjoint?, set])
when false
assert_not_send([set, :intersect?, other])
assert_not_send([set, :intersect?, other.to_a])
assert_not_send([other, :intersect?, set])
assert_send([set, :disjoint?, other])
assert_send([set, :disjoint?, other.to_a])
assert_send([other, :disjoint?, set])
when Class
assert_raise(expected) {
Expand All @@ -378,7 +382,7 @@ def test_intersect?
set = Set[3,4,5]

assert_intersect(ArgumentError, set, 3)
assert_intersect(ArgumentError, set, [2,4,6])
assert_intersect(true, set, Set[2,4,6])

assert_intersect(true, set, set)
assert_intersect(true, set, Set[2,4])
Expand Down