在ruby中使用散列进行字符串插值

BIl*_*han 11 ruby string-formatting

我的目标是用散列值替换字符串中的键.我是这样做的:

"hello %{name}, today is %{day}" % {name: "Tim", day: "Monday"}
Run Code Online (Sandbox Code Playgroud)

如果散列中缺少字符串中的键:

"hello %{name}, today is %{day}" % {name: "Tim", city: "Lahore"}
Run Code Online (Sandbox Code Playgroud)

然后它会抛出一个错误.

KeyError: key{day} not found
Run Code Online (Sandbox Code Playgroud)

预期结果应为:

"hello Tim, today is %{day}" or "hello Tim, today is "
Run Code Online (Sandbox Code Playgroud)

有人可以指导我的方向,只更换匹配的键而不会丢失任何错误?

Ste*_*fan 17

从Ruby 2.3开始,%通过default=以下方式设置默认值:

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

'hello %{name}, today is %{day}' % hash
#=> "hello Tim, today is "
Run Code Online (Sandbox Code Playgroud)

或动态默认设置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}"
Run Code Online (Sandbox Code Playgroud)

请注意,只有缺少的键ie :day传递给proc.因此,它不知道您是否使用%{day}%<day>s在您的格式字符串中可能导致不同的输出:

'hello %{name}, today is %<day>s' % hash
#=> "hello Tim, today is %{day}"
Run Code Online (Sandbox Code Playgroud)