diff --git string.c string.c index 9079387..47d6f42 100644 --- string.c +++ string.c @@ -4965,7 +4965,11 @@ rb_str_sub_bang(int argc, VALUE *argv, VALUE str) repl = rb_obj_as_string(rb_yield(match0)); } else { - repl = rb_hash_aref(hash, rb_str_subseq(str, beg0, end0 - beg0)); + VALUE key = rb_str_subseq(str, beg0, end0 - beg0); + repl = rb_hash_aref(hash, key); + if (NIL_P(repl)) { + repl = rb_hash_aref(hash, rb_to_symbol(key)); + } repl = rb_obj_as_string(repl); } str_mod_check(str, p, len); @@ -5140,7 +5144,11 @@ str_gsub(int argc, VALUE *argv, VALUE str, int bang) val = rb_obj_as_string(rb_yield(match0)); } else { - val = rb_hash_aref(hash, rb_str_subseq(str, beg0, end0 - beg0)); + VALUE key = rb_str_subseq(str, beg0, end0 - beg0); + val = rb_hash_aref(hash, key); + if (NIL_P(val)) { + val = rb_hash_aref(hash, rb_to_symbol(key)); + } val = rb_obj_as_string(val); } str_mod_check(str, sp, slen); diff --git test/-ext-/string/test_gsub.rb test/-ext-/string/test_gsub.rb new file mode 100644 index 0000000..27eb350 --- /dev/null +++ test/-ext-/string/test_gsub.rb @@ -0,0 +1,18 @@ +require 'test/unit' +require "-test-/string" + +class Test_StringGsub < Test::Unit::TestCase + def test_gsub_with_hash + hash = {'b'=>'B', 'c'=>'C'} + assert_equal("abcabc".gsub(/[bc]/, hash), "aBCaBC") + assert_equal("cbacba".gsub(/[bc]/, hash), "CBaCBa") + assert_equal("abcabc".gsub(/[ac]/, hash), "bCbC") + end + + def test_gsub_with_symbol_key_hash + hash = {b: 'B', c: 'C'} + assert_equal("abcabc".gsub(/[bc]/, hash), "aBCaBC") + assert_equal("cbacba".gsub(/[bc]/, hash), "CBaCBa") + assert_equal("abcabc".gsub(/[ac]/, hash), "bCbC") + end +end diff --git test/-ext-/string/test_sub.rb test/-ext-/string/test_sub.rb new file mode 100644 index 0000000..a70832c --- /dev/null +++ test/-ext-/string/test_sub.rb @@ -0,0 +1,18 @@ +require 'test/unit' +require "-test-/string" + +class Test_StringSub < Test::Unit::TestCase + def test_sub_with_hash + hash = {'b'=>'B', 'c'=>'C'} + assert_equal("abcabc".sub(/[bc]/, hash), "aBcabc") + assert_equal("cbacba".sub(/[bc]/, hash), "Cbacba") + assert_equal("abcabc".sub(/[ac]/, hash), "bcabc") + end + + def test_sub_with_symbol_key_hash + hash = {b: 'B', c: 'C'} + assert_equal("abcabc".sub(/[bc]/, hash), "aBcabc") + assert_equal("cbacba".sub(/[bc]/, hash), "Cbacba") + assert_equal("abcabc".sub(/[ac]/, hash), "bcabc") + end +end