From 0db54957565c08bef2f8a8c2f96f326066c724f9 Mon Sep 17 00:00:00 2001 From: Li Ellis Gallardo Date: Tue, 29 May 2012 20:29:40 -0500 Subject: [PATCH] array.c: added method that verifies if an Array is part of another --- array.c | 21 +++++++++++++++++++++ test/ruby/test_array.rb | 14 ++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/array.c b/array.c index 59572ecaadb965..da63e804ed3a8f 100644 --- a/array.c +++ b/array.c @@ -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 @@ -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 16875894ef7d2e..68bd9137d7f007 100644 --- a/test/ruby/test_array.rb +++ b/test/ruby/test_array.rb @@ -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 pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy