From 5de82e6dc219e51d2c270cc7f4c54e8b9ab7de49 Mon Sep 17 00:00:00 2001 From: zimbatm Date: Mon, 2 Mar 2015 16:08:09 +0000 Subject: [PATCH] Add a default empty string to string replacements New usages: "foo".sub("o") #=> "fo" "foo".gsub("o") #=> "f" Applies to the bang versions as well. This commit changes the return values of String#gsub! call with a single argument and no block from an Enumerator to a String. Before: "foo".gsub("o") #=> # --- string.c | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/string.c b/string.c index 9419e31..6fca843 100644 --- a/string.c +++ b/string.c @@ -4087,7 +4087,7 @@ rb_pat_search(VALUE pat, VALUE str, long pos, int set_backref_str) /* * call-seq: - * str.sub!(pattern, replacement) -> str or nil + * str.sub!(pattern, replacement='') -> str or nil * str.sub!(pattern) {|match| block } -> str or nil * * Performs the same substitution as String#sub in-place. @@ -4103,12 +4103,16 @@ rb_str_sub_bang(int argc, VALUE *argv, VALUE str) int iter = 0; int tainted = 0; long plen; - int min_arity = rb_block_given_p() ? 1 : 2; long beg; - rb_check_arity(argc, min_arity, 2); + rb_check_arity(argc, 1, 2); if (argc == 1) { - iter = 1; + if (rb_block_given_p()) { + iter = 1; + } + else { + repl = rb_str_new("", 0); + } } else { repl = argv[1]; @@ -4210,7 +4214,7 @@ rb_str_sub_bang(int argc, VALUE *argv, VALUE str) /* * call-seq: - * str.sub(pattern, replacement) -> new_str + * str.sub(pattern, replacement='') -> new_str * str.sub(pattern, hash) -> new_str * str.sub(pattern) {|match| block } -> new_str * @@ -4271,8 +4275,13 @@ str_gsub(int argc, VALUE *argv, VALUE str, int bang) switch (argc) { case 1: - RETURN_ENUMERATOR(str, argc, argv); - mode = ITER; + if (rb_block_given_p()) { + RETURN_ENUMERATOR(str, argc, argv); + mode = ITER; + } + else { + repl = rb_str_new("", 0); + } break; case 2: repl = argv[1]; -- 2.3.1