mercredi 23 août 2017

String interpolation with hash in ruby

My aim is to replace certain keys in string with values in hash. I am doing it like this

"hello %{name}, today is %{day}" % {name: "Tim", day: "Monday"}

This works fine as it finds all the keys present in the hash to be replaced in the string. If we dont have the key in the hash corresponding to the string. It will throw an error.

"hello %{name}, today is %{day}" % {name: "Tim", city: "Lahore"}

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.

Aucun commentaire:

Enregistrer un commentaire