From 7cd78f1d05372ff8ba333a7e5f2513456d4f4526 Mon Sep 17 00:00:00 2001 From: matz Date: Thu, 20 Sep 2007 17:14:01 +0000 Subject: * re.c (rb_reg_match_m): evaluate a block if match. it would make condition statement much shorter, if no else clause is needed. * string.c (rb_str_match_m): ditto. git-svn-id: http://svn.ruby-lang.org/repos/ruby/trunk@13475 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- string.c | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) (limited to 'string.c') diff --git a/string.c b/string.c index 0a50f174f..1cad0f8bf 100644 --- a/string.c +++ b/string.c @@ -1547,17 +1547,34 @@ static VALUE get_pat(VALUE, int); * 'hello'.match('(.)\1')[0] #=> "ll" * 'hello'.match(/(.)\1/)[0] #=> "ll" * 'hello'.match('xx') #=> nil + * + * If a block is given, invoke the block with MatchData if match succeed, so + * that you can write + * + * str.match(pat) {|m| ...} + * + * instead of + * + * if m = str.match(pat) + * ... + * end + * + * The retuen value is a value from block exection in this case. */ static VALUE rb_str_match_m(int argc, VALUE *argv, VALUE str) { - VALUE re; + VALUE re, result; if (argc < 1) rb_raise(rb_eArgError, "wrong number of arguments (%d for 1)", argc); re = argv[0]; argv[0] = str; - return rb_funcall2(get_pat(re, 0), rb_intern("match"), argc, argv); + result = rb_funcall2(get_pat(re, 0), rb_intern("match"), argc, argv); + if (!NIL_P(result) && rb_block_given_p()) { + return rb_yield(result); + } + return result; } static int -- cgit