commit 444e941ce068d17017cf8ef7b25543271eff133f Author: Li Ellis Gallardo Date: Tue May 29 20:29:40 2012 -0500 array.c: added method that verifies if an Array is part of another diff --git a/array.c b/array.c index 59572ec..da63e80 100644 --- a/array.c +++ b/array.c @@ -4686,6 +4686,26 @@ rb_ary_drop_while(VALUE ary) } /* + * 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 * assumed to be relative to the end of the array---that is, an index of -1 @@ -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")); diff --git a/test/ruby/test_array.rb b/test/ruby/test_array.rb index 1687589..68bd913 100644 --- a/test/ruby/test_array.rb +++ b/test/ruby/test_array.rb @@ -2184,4 +2184,18 @@ class TestArray < Test::Unit::TestCase 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