Project

General

Profile

Feature #6515 ยป feature_6515_array_part_of.patch

zzak (Zachary Scott), 05/30/2012 09:00 PM

View differences:

array.c
4686 4686
}
4687 4687

  
4688 4688
/*
4689
 *  call-seq:
4690
 *     ary.part_of? other_ary   ->   bool
4691
 *
4692
 *  Array 'A' is part of another array 'B' if
4693
 *  each element from 'A' are include in 'B'
4694
 *
4695
 *  [ "a", "c" ].part_of? [ "a", "b", "c" ]    #=> true
4696
 *  [ "a", "d" ].part_of? [ "a", "b", "c" ]    #=> false
4697
 *  [].part_of []                              #=> true
4698
 *
4699
 */
4700

  
4701
static VALUE
4702
rb_ary_part_of(VALUE ary1, VALUE ary2)
4703
{
4704

  
4705
    if (ary1 == ary2) return Qtrue;
4706
    VALUE ary3, ary4;
4707
    ary3 = rb_ary_and(ary1, ary2);
4708
    ary4 = rb_ary_diff(ary1, ary3);
4709
    return rb_ary_empty_p(ary4);
4710
}
4711

  
4712
/*
4689 4713
 * Arrays are ordered, integer-indexed collections of any object.
4690 4714
 * Array indexing starts at 0, as in C or Java.  A negative index is
4691 4715
 * assumed to be relative to the end of the array---that is, an index of -1
......
5020 5044
    rb_define_method(rb_cArray, "take_while", rb_ary_take_while, 0);
5021 5045
    rb_define_method(rb_cArray, "drop", rb_ary_drop, 1);
5022 5046
    rb_define_method(rb_cArray, "drop_while", rb_ary_drop_while, 0);
5047
    rb_define_method(rb_cArray, "part_of?", rb_ary_part_of, 1);
5023 5048

  
5024 5049
    id_cmp = rb_intern("<=>");
5025 5050
    sym_random = ID2SYM(rb_intern("random"));
test/ruby/test_array.rb
2184 2184
    a = [1,2,3]
2185 2185
    assert_raise(ArgumentError) { a.rotate!(1, 1) }
2186 2186
  end
2187

  
2188
  def test_part_of?
2189
    assert_equal(true, [].part_of?([]))
2190
    a = [1, 3, 4]
2191
    b = [1, 2, 3, 4, 5]
2192
    assert_equal(true, a.part_of?(b))
2193
    assert_equal(false, b.part_of?(a))
2194
    a = %w( ant bat cat dog )
2195
    b = %w( dog cat bat ant )
2196
    assert_equal(true, a.part_of?(b))
2197
    assert_equal(true, b.part_of?(a))
2198
    assert_raise(TypeError) { a.part_of? 1 }
2199
    assert_raise(ArgumentError) { a.part_of?() }
2200
  end
2187 2201
end
2188
-