summaryrefslogtreecommitdiff
path: root/array.c
diff options
context:
space:
mode:
authorPrajjwal Singh <sin@prajjwal.com>2019-10-07 10:42:29 +0530
committerNobuyoshi Nakada <nobu@ruby-lang.org>2019-10-07 15:59:12 +0900
commitc8542ab484efb6ee0009cd081789d9a68f482483 (patch)
treef8c00b416b4ff3c7fae2cb534338162066201b17 /array.c
parentd4ec37f69e3bd6f88725fe1075daa2e5f58c2aec (diff)
Add: Array#intersection method
Notes
Notes: Merged: https://github.com/ruby/ruby/pull/2533
Diffstat (limited to 'array.c')
-rw-r--r--array.c31
1 files changed, 31 insertions, 0 deletions
diff --git a/array.c b/array.c
index 9235bf22e8..341edb5aaf 100644
--- a/array.c
+++ b/array.c
@@ -4668,6 +4668,36 @@ rb_ary_and(VALUE ary1, VALUE ary2)
return ary3;
}
+/*
+ * call-seq:
+ * ary.intersection(other_ary1, other_ary2, ...) -> new_ary
+ *
+ * Set Intersection --- Returns a new array containing unique elements common
+ * to +self+ and <code>other_ary</code>s. Order is preserved from the original
+ * array.
+ *
+ * It compares elements using their #hash and #eql? methods for efficiency.
+ *
+ * [ 1, 1, 3, 5 ].intersection([ 3, 2, 1 ]) # => [ 1, 3 ]
+ * [ "a", "b", "z" ].intersection([ "a", "b", "c" ], [ "b" ]) # => [ "b" ]
+ * [ "a" ].intersection #=> [ "a" ]
+ *
+ * See also Array#&.
+ */
+
+static VALUE
+rb_ary_intersection_multi(int argc, VALUE *argv, VALUE ary)
+{
+ VALUE result = rb_ary_dup(ary);
+ int i;
+
+ for (i = 0; i < argc; i++) {
+ result = rb_ary_and(result, argv[i]);
+ }
+
+ return result;
+}
+
static int
ary_hash_orset(st_data_t *key, st_data_t *value, st_data_t arg, int existing)
{
@@ -6928,6 +6958,7 @@ Init_Array(void)
rb_define_method(rb_cArray, "concat", rb_ary_concat_multi, -1);
rb_define_method(rb_cArray, "union", rb_ary_union_multi, -1);
rb_define_method(rb_cArray, "difference", rb_ary_difference_multi, -1);
+ rb_define_method(rb_cArray, "intersection", rb_ary_intersection_multi, -1);
rb_define_method(rb_cArray, "<<", rb_ary_push, 1);
rb_define_method(rb_cArray, "push", rb_ary_push_m, -1);
rb_define_alias(rb_cArray, "append", "push");