BIlal Khan BIlal Khan - 1 month ago 11
Ruby Question

String interpolation with hash in ruby

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?

Answer Source

You can give your hash a static default value via default=:

hash = {name: 'Tim', city: 'Lahore'}
hash.default = ''

'hello %{name}, today is %{day}' % hash
#=> "hello Tim, today is "

or a dynamic default value by setting 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}"