Issue #15927 has been updated by sawa (Tsuyoshi Sawada).


ashmaroli (Ashwin Maroli) wrote:
> One use-case would be where the Data used by `sprintf` is generated at runtime:
> ```ruby
> require 'yaml'
> 
> # contents of 'path/to/config.yml':
> #
> # ---
> # title: Hello World
> # author: John Doe
> # url: "https://www.example.com/blog"
> #
> 
> config = YAML.load_file('path/to/config.yml')
> # config == {"title"=>"Hello World", "author"=>"John Doe", "url"=>"https://www.example.com/blog"}
> 
> # This will fail. The alternative would be to convert the string keys to symbols beforehand.
> "title = %{title}" % config
> [...]
> ```

I do not think that is the duty of string format.

If the YAML file is written by a Ruby program, then you should have saved the keys as symbols from the beginning, and you would not have such problem. If you are hand-writing the YAML file, there is a Ruby-specific way to explicitly write symbol keys in YAML, so check the documentation. If you need to write YAML file using a non-Ruby language and can not avoid having the keys written as strngs, then rather than betting on this feature request, you should make a different feature request that asks for a `:symbolize_names` option for YAML, as in JSON.


----------------------------------------
Feature #15927: Allow string keys to be used for String#% and sprintf methods
https://bugs.ruby-lang.org/issues/15927#change-78620

* Author: luke-gru (Luke Gruber)
* Status: Open
* Priority: Normal
* Assignee: 
* Target version: 
----------------------------------------
Right now, in the methods sprintf() and String#%, only symbol keys can be used for named interpolation. For example (from the example documentation):

"foo = %{foo}" % { :foo => 'bar' }        #=> "foo = bar"

String keys do not work like this:

"foo = %{foo}" % { 'foo' => 'bar' }        #=> raises KeyError

I think string keys should work just the same as symbol keys here.

I've created a PR on github for this, perhaps misguidedly, but if can be found here: https://github.com/ruby/ruby/pull/2238

My argument for this feature is that String#gsub() and family works with string keys if given a Hash, for example:

"chocolate ice cream".gsub(/\bc/, { 'c' => 'C' }) #=> 'Chocolate ice Cream'

Also, I don't like having to symbolize keys in strings unnecessarily, but maybe that just goes back to when
Ruby couldn't GC some symbols.





-- 
https://bugs.ruby-lang.org/

Unsubscribe: <mailto:ruby-core-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>