Ruby中的字符串插值

ylamdve6  于 12个月前  发布在  Ruby
关注(0)|答案(4)|浏览(82)

我的目标是将字符串中的键替换为哈希值。我是这样做的:

"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 "

有人可以指导我在一个方向,以取代只有匹配的关键没有抛出任何错误?

3duebb1j

3duebb1j1#

从Ruby 2.3开始,%遵循通过default=设置的默认值:

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

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

或通过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}"

请注意,只有缺少的密钥,即:day被传递到proc。因此,它不知道您在格式字符串中使用的是%{day}还是%<day>s,这可能会导致不同的输出:

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

yhuiod9q2#

你可以设置一个默认的哈希值:

h = {name: "Tim", city: "Lahore"}
h.default = "No key"
p "hello %{name}, today is %{day}" % h #=>"hello Tim, today is No key"
gev0vcfq

gev0vcfq3#

我有一个带空格的散列键,它在将键转换为符号后工作。
Hash with String keys(它返回了一个插值错误):

hash = {"First Name" => "Allama", "Last Name" => "Iqbal"}

将散列键转换为Symbols对我来说很有效:

hash = {:"First Name" => "Allama", :"Last Name" => "Iqbal"}
hash.default = ''

'The %{First Name} %{Last Name} was a great poet.' % hash

// The Allama Iqbal was a great poet.
yquaqz18

yquaqz184#

我知道这是旧的,但我最终使我的需要实用程序。这是我的Gist https://gist.github.com/Genkilabs/71b479e1b1300a581a85e047db1cbb43

#@param String with %{key} interpolation fields
  #@param Hash or Rails Model
  #@returns String original with any keys replaced if they are in the hash, others ignored
  def self.interpolate str, obj
    #For the hash, we need to re-key the hash to be sure, and add default to skip missing interpolations
    safe_hash = (defined?(obj.attributes) ? obj.attributes : obj.to_h).symbolize_keys
    safe_hash.default_proc = proc{|h, k| "%{#{k}}" }
    #On the string side, safeguard any place ther is a symbol inside an interpolated field
    str.gsub('%{:', '%{') % safe_hash
  end

相关问题