I am using the percent string formatting like so:
'fetching imap (%<host>s/%<user>s port=%<port>s...' % options
This works fine when the options
hash has symbol keys { host: 'example.com' }
, but raises a KeyError
when it has string keys { 'host' => 'example.com' }
:
KeyError: key<host> not found
This is problematic because Rails’ HashWithIndifferentAccess
uses string keys by default. If using ActiveSupport, one solution is to call symbolize_keys
on the hash.
Is there an alternative way to make the String#%
method try string keys as well as symbol keys?
Is this a bug in Ruby that deserves a bug report? Or are there reasons for enforcing this behavior, like the edge case where both :host
and 'host'
keys exist?