Skip to content

array.c: added method that verifies if an Array is part of another #127

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
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
21 changes: 21 additions & 0 deletions array.c
Original file line number Diff line number Diff line change
Expand Up @@ -4685,6 +4685,26 @@ rb_ary_drop_while(VALUE ary)
return rb_ary_drop(ary, LONG2FIX(i));
}

/*
* call-seq:
* ary.part_of? other_ary -> bool
*
* Array 'A' is part of another array 'B' if
* each element from 'A' are included in 'B'
*
* [ "a", "c" ].part_of? [ "a", "b", "c" ] #=> true
* [ "a", "d" ].part_of? [ "a", "b", "c" ] #=> false
* [].part_of [] #=> true
*
*/

static VALUE
rb_ary_part_of(VALUE ary1, VALUE ary2)
{
ary2 = rb_ary_diff(ary1, ary2);
return rb_ary_empty_p(ary2);
}

/*
* Arrays are ordered, integer-indexed collections of any object.
* Array indexing starts at 0, as in C or Java. A negative index is
Expand Down Expand Up @@ -5020,6 +5040,7 @@ Init_Array(void)
rb_define_method(rb_cArray, "take_while", rb_ary_take_while, 0);
rb_define_method(rb_cArray, "drop", rb_ary_drop, 1);
rb_define_method(rb_cArray, "drop_while", rb_ary_drop_while, 0);
rb_define_method(rb_cArray, "part_of?", rb_ary_part_of, 1);

id_cmp = rb_intern("<=>");
sym_random = ID2SYM(rb_intern("random"));
Expand Down
14 changes: 14 additions & 0 deletions test/ruby/test_array.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2184,4 +2184,18 @@ def test_rotate!
a = [1,2,3]
assert_raise(ArgumentError) { a.rotate!(1, 1) }
end

def test_part_of?
assert_equal(true, [].part_of?([]))
a = [1, 3, 4]
b = [1, 2, 3, 4, 5]
assert_equal(true, a.part_of?(b))
assert_equal(false, b.part_of?(a))
a = %w( ant bat cat dog )
b = %w( dog cat bat ant )
assert_equal(true, a.part_of?(b))
assert_equal(true, b.part_of?(a))
assert_raise(TypeError) { a.part_of? 1 }
assert_raise(ArgumentError) { a.part_of?() }
end
end