我的目标是将字符串中的键替换为哈希值。我是这样做的:
"hello %{name}, today is %{day}" % {name: "Tim", day: "Monday"}
如果哈希中缺少字符串中的键:
"hello %{name}, today is %{day}" % {name: "Tim", city: "Lahore"}
则它将抛出错误。
KeyError: key{day} not found
预期结果应为:
"hello Tim, today is %{day}" or "hello Tim, today is "
有人可以指导我在一个方向,以取代只有匹配的关键没有抛出任何错误?
4条答案
按热度按时间3duebb1j1#
从Ruby 2.3开始,
%
遵循通过default=
设置的默认值:或通过
default_proc=
设置的动态默认值:请注意,只有缺少的密钥,即
:day
被传递到proc。因此,它不知道您在格式字符串中使用的是%{day}
还是%<day>s
,这可能会导致不同的输出:yhuiod9q2#
你可以设置一个默认的哈希值:
gev0vcfq3#
我有一个带空格的散列键,它在将键转换为符号后工作。
Hash with String keys(它返回了一个插值错误):
将散列键转换为Symbols对我来说很有效:
yquaqz184#
我知道这是旧的,但我最终使我的需要实用程序。这是我的Gist https://gist.github.com/Genkilabs/71b479e1b1300a581a85e047db1cbb43