Today’s Ruby Tuesday is on Set#disjoint?.
To start using Sets, we first need to require Set
.
require 'set'
Set#disjoint?
is useful when you want to make sure a group of items is not in another group of items.
Without using Set#disjoint?
you would probably be writing something like the following:
[1, 3, 1, 5, 7].none? { |item| [2, 4, 6, 8].include? item } # => true
While this works, it does not make the intent of what you are trying to do explicit, which is where Set#disjoint?
comes in.
Set#disjoint?
operates against a set, and takes another Set
as it’s argument, and checks to see if there is no common element between the two sets.
[1, 3, 1, 5, 7].to_set.disjoint? [2, 4, 6, 8].to_set # => true [1, 2, 3].to_set.disjoint? [1, 3, 5, 7].to_set # => false
If a nil
is present in both sets, Set#disjoint?
treats the nil
s as equal and returns false.
[2, nil].to_set.disjoint? [1, 3, 5, 7, nil].to_set => false
Set#disjoint?
works against empty sets as well.
[].to_set.disjoint? [1, 2, 3].to_set # => true [1, 2, 3].to_set.disjoint? [].to_set # => true
If two empty sets are passed to Set#disjoint?
, it returns true, as both sets have no elements, and therefore no elements in common.
[].to_set.disjoint? [].to_set # => true
–Proctor