From f1f12658ee64d443e17cd7e39e12556123580817 Mon Sep 17 00:00:00 2001 From: knu Date: Fri, 20 Mar 2009 09:43:24 +0000 Subject: * array.c (Array#try_convert): New method backported from 1.9. * hash.c (Hash#try_convert): New method backported from 1.9. * io.c (IO#try_convert): New method backported from 1.9. * re.c (Regexp#try_convert): New method backported from 1.9. * string.c (String#try_convert): New method backported from 1.9. git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/branches/ruby_1_8@23018 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- array.c | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) (limited to 'array.c') diff --git a/array.c b/array.c index a1bfeeedd7..0ca0924d1b 100644 --- a/array.c +++ b/array.c @@ -268,6 +268,33 @@ rb_check_array_type(ary) return rb_check_convert_type(ary, T_ARRAY, "Array", "to_ary"); } +/* + * call-seq: + * Array.try_convert(obj) -> array or nil + * + * Try to convert obj into an array, using to_ary method. + * Returns converted array or nil if obj cannot be converted + * for any reason. This method is to check if an argument is an + * array. + * + * Array.try_convert([1]) # => [1] + * Array.try_convert("1") # => nil + * + * if tmp = Array.try_convert(arg) + * # the argument is an array + * elsif tmp = String.try_convert(arg) + * # the argument is a string + * end + * + */ + +static VALUE +rb_ary_s_try_convert(dummy, ary) + VALUE dummy, ary; +{ + return rb_check_array_type(ary); +} + static VALUE rb_ary_replace _((VALUE, VALUE)); /* @@ -3836,6 +3863,7 @@ Init_Array() rb_define_alloc_func(rb_cArray, ary_alloc); rb_define_singleton_method(rb_cArray, "[]", rb_ary_s_create, -1); + rb_define_singleton_method(rb_cArray, "try_convert", rb_ary_s_try_convert, 1); rb_define_method(rb_cArray, "initialize", rb_ary_initialize, -1); rb_define_method(rb_cArray, "initialize_copy", rb_ary_replace, 1); -- cgit v1.2.3