From a05337f14d373d99da2b150b96a88800a0b7c018 Mon Sep 17 00:00:00 2001 From: nobu Date: Fri, 15 Feb 2008 09:23:55 +0000 Subject: * string.c (rb_str_sub_bang, str_gsub): allows hash for replacement. git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@15487 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- string.c | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) (limited to 'string.c') diff --git a/string.c b/string.c index f0ac3844e3..1d94ca29f7 100644 --- a/string.c +++ b/string.c @@ -2783,7 +2783,7 @@ get_pat(VALUE pat, int quote) static VALUE rb_str_sub_bang(int argc, VALUE *argv, VALUE str) { - VALUE pat, repl, match; + VALUE pat, repl, match, hash = Qnil; struct re_registers *regs; int iter = 0; int tainted = 0; @@ -2794,7 +2794,10 @@ rb_str_sub_bang(int argc, VALUE *argv, VALUE str) } else if (argc == 2) { repl = argv[1]; - StringValue(repl); + hash = rb_check_convert_type(argv[1], T_HASH, "Hash", "to_hash"); + if (NIL_P(hash)) { + StringValue(repl); + } if (OBJ_TAINTED(repl)) tainted = 1; } else { @@ -2818,6 +2821,9 @@ rb_str_sub_bang(int argc, VALUE *argv, VALUE str) str_frozen_check(str); rb_backref_set(match); } + else if (!NIL_P(hash)) { + repl = rb_hash_aref(hash, rb_str_subseq(str, BEG(0), END(0) - BEG(0))); + } else { repl = rb_reg_regsub(repl, str, regs, pat); } @@ -2904,7 +2910,7 @@ rb_str_sub(int argc, VALUE *argv, VALUE str) static VALUE str_gsub(int argc, VALUE *argv, VALUE str, int bang) { - VALUE pat, val, repl, match, dest; + VALUE pat, val, repl, match, dest, hash = Qnil; struct re_registers *regs; long beg, n; long offset, blen, slen, len; @@ -2920,7 +2926,10 @@ str_gsub(int argc, VALUE *argv, VALUE str, int bang) break; case 2: repl = argv[1]; - StringValue(repl); + hash = rb_check_convert_type(argv[1], T_HASH, "Hash", "to_hash"); + if (NIL_P(hash)) { + StringValue(repl); + } if (OBJ_TAINTED(repl)) tainted = 1; break; default: @@ -2956,6 +2965,9 @@ str_gsub(int argc, VALUE *argv, VALUE str, int bang) } rb_backref_set(match); } + else if (!NIL_P(hash)) { + val = rb_hash_aref(hash, rb_str_subseq(str, BEG(0), END(0) - BEG(0))); + } else { val = rb_reg_regsub(repl, str, regs, pat); } -- cgit v1.2.3