From 56ee304dd8dbf062a80d7a2847f7f4c543780708 Mon Sep 17 00:00:00 2001 From: matz Date: Fri, 24 Aug 2007 17:47:09 +0000 Subject: * array.c (rb_ary_s_try_convert): a new class method to convert object or nil if it's not target-type. this mechanism is used to convert types in the C implemented methods. * hash.c (rb_hash_s_try_convert): ditto. * io.c (rb_io_s_try_convert): ditto. * re.c (rb_reg_s_try_convert): ditto. * string.c (rb_str_s_try_convert): ditto. git-svn-id: http://svn.ruby-lang.org/repos/ruby/trunk@13251 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- string.c | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) (limited to 'string.c') diff --git a/string.c b/string.c index efb380feb..dd2d7473a 100644 --- a/string.c +++ b/string.c @@ -615,6 +615,23 @@ rb_check_string_type(VALUE str) return str; } +/* + * call-seq: + * String.try_convert(obj) -> string or nil + * + * Try to convert obj into a String, using to_str method. + * Returns converted regexp or nil if obj cannot be converted + * for any reason. + * + * String.try_convert("str") # => str + * String.try_convert(/re/) # => nil + */ +static VALUE +rb_str_s_try_convert(VALUE dummy, VALUE str) +{ + return rb_check_string_type(str); +} + VALUE rb_str_substr(VALUE str, long beg, long len) { @@ -4877,6 +4894,7 @@ Init_String(void) rb_cString = rb_define_class("String", rb_cObject); rb_include_module(rb_cString, rb_mComparable); rb_define_alloc_func(rb_cString, str_alloc); + rb_define_singleton_method(rb_cString, "try_convert", rb_str_s_try_convert, 1); rb_define_method(rb_cString, "initialize", rb_str_init, -1); rb_define_method(rb_cString, "initialize_copy", rb_str_replace, 1); rb_define_method(rb_cString, "<=>", rb_str_cmp_m, 1); -- cgit