Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 367
BIlal Khan Avatar asked Aug 23 '17 09:08

BIlal Khan


1 Answers

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}"
like image 64
Stefan Avatar answered Sep 20 '22 13:09

Stefan