Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
instance method
Set#&
(::_Each[A]) -> self
self & enumerable → new_set
set.c
View on GitHub ↗
static VALUE
set_i_intersection(VALUE set, VALUE other)
{
VALUE new_set = set_s_alloc(rb_obj_class(set));
if (RSET_COMPARE_BY_IDENTITY(set)) {
set_i_compare_by_identity(new_set);
}
set_table *stable = RSET_TABLE(set);
set_table *ntable = RSET_TABLE(new_set);
VALUE data;
if (rb_obj_is_kind_of(other, rb_cSet)) {
set_table *otable = RSET_TABLE(other);
if (set_table_size(stable) >= set_table_size(otable)) {
/* Swap so we iterate over the smaller set */
otable = stable;
set = other;
}
*NEW_PARTIAL_MEMO_FOR(struct set_intersection_data, data, into) = (struct set_intersection_data) {
.set = new_set,
.other_set = other,
.new_set = new_set,
.into = ntable,
.other = otable,
};
set_iter(set, set_intersection_i, (st_data_t)data);
}
else {
*NEW_PARTIAL_MEMO_FOR(struct set_intersection_data, data, into) = (struct set_intersection_data) {
.set = new_set,
.other_set = other,
.new_set = new_set,
.into = ntable,
.other = stable,
};
rb_block_call(other, enum_method_id(other), 0, 0, set_intersection_block, data);
}
RB_GC_GUARD(data);
return new_set;
}
Returns a new set containing the intersection of self and enumerable; that is, containing all elements common to both, with no duplicates. Argument enumerable must be an Enumerable object:
Example
set = Set[*(0..6), *%w[ a b c]] # => Set[0, 1, 2, 3, 4, 5, 6, "a", "b", "c"] set & ['c', 6, 8, 4] # => Set["c", 6, 4] set & [:foo, :bar] # => Set[] # No elements in common.
Related: see Methods for Set Operations.