My aim is to replace keys in a string with values in hash. I am doing it like this:
"hello %{name}, today is %{day}" % {name: "Tim", day: "Monday"}
If a key in the string in missing in the hash:
"hello %{name}, today is %{day}" % {name: "Tim", city: "Lahore"}
then it will throw an error.
KeyError: key{day} not found
Expected result should be:
"hello Tim, today is %{day}" or "hello Tim, today is "
Can someone guide me in a direction to replace only the matching keys without throwing any errors?
Starting with Ruby 2.3, %
honors default values set via default=
:
hash = {name: 'Tim', city: 'Lahore'}
hash.default = ''
'hello %{name}, today is %{day}' % hash
#=> "hello Tim, today is "
or dynamic defaults set via default_proc=
:
hash = {name: 'Tim', city: 'Lahore'}
hash.default_proc = proc { |h, k| "%{#{k}}" }
'hello %{name}, today is %{day}' % hash
#=> "hello Tim, today is %{day}"
Note that only the missing key i.e. :day
is passed to the proc. It is therefore unaware of whether you use %{day}
or %<day>s
in your format string which might result in a different output:
'hello %{name}, today is %<day>s' % hash
#=> "hello Tim, today is %{day}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With