From: nobu@... Date: 2015-11-08T07:58:50+00:00 Subject: [ruby-core:71386] [Ruby trunk - Feature #11661] [Feedback] sprintf causes a KeyError instead of using a default value for hash substitution Issue #11661 has been updated by Nobuyoshi Nakada. Tracker changed from Bug to Feature Status changed from Open to Feedback [GH-1087](https://github.com/ruby/ruby/pull/1087) doesn't work properly with a default proc expecting an argument, but segfaults. My patch. ~~~diff diff --git i/sprintf.c w/sprintf.c index 705d3ce..eee5695 100644 --- i/sprintf.c +++ w/sprintf.c @@ -605,13 +605,10 @@ rb_str_format(int argc, const VALUE *argv, VALUE fmt) } CHECKNAMEARG(start, len, enc); get_hash(&hash, argc, argv); - sym = rb_check_symbol_cstr(start + 1, - len - 2 /* without parenthesis */, - enc); - if (sym != Qnil) nextvalue = rb_hash_lookup2(hash, sym, Qundef); - if (nextvalue == Qundef) { - rb_enc_raise(enc, rb_eKeyError, "key%.*s not found", len, start); - } + sym = rb_cstr_intern(start + 1, + len - 2 /* without parenthesis */, + enc); + nextvalue = rb_hash_aref(hash, sym); if (term == '}') goto format_s; p++; goto retry; ~~~ ---------------------------------------- Feature #11661: sprintf causes a KeyError instead of using a default value for hash substitution https://bugs.ruby-lang.org/issues/11661#change-54757 * Author: Eddy Luten * Status: Feedback * Priority: Normal * Assignee: Yukihiro Matsumoto ---------------------------------------- When using a format string that substitutes hash values (or using the `%` operator on a string), instead of using the Hash's default value if a key is not present, it causes a KeyError. As an end-user, to get around this, my hash needs to know about all the possible keys ahead of time and pre-assign a value to them or handle the KeyError. Logically, I would assume that the `sprintf` implementation would use the default Hash value. I wanted to open this issue to see what your collective thoughts were on this since I have a fork running locally that fixes this issue and was wondering if I could send a patch/PR for this. This issue is reproducible using the following code: ```ruby my_hash = Hash.new('world') puts "hello %{location}" % my_hash # expecting "hello world" # "KeyError: key{location} not found" ``` -- https://bugs.ruby-lang.org/