2017-08-23 237 views
4

我的目标是用字符串中的值替换散列值。我这样做是这样的:红宝石散列字符串插值

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

有人能指导我的方向仅替换匹配的密钥没有抛出任何错误?

+0

是什么在第二种情况下,即您预期的结果如果钥匙丢失? – Stefan

+0

感谢您的关注。预期的回应可以是“你好Tim,今天是%{day}”或者“你好,Tim,今天是”。我认为第二个将是首选 –

回答

9

使用Ruby 2.3,通过default=设置%荣誉默认值开始:通过default_proc=设置

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

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

或动态默认值:只有即:day缺少的关键是传递给

hash = {name: 'Tim', city: 'Lahore'} 
hash.default_proc = proc { |h, k| "%{#{k}}" } 

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

注PROC。因此,不知道你是否在您的格式字符串中使用%{day}%<day>s这可能会导致不同的输出:

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

这不会工作在红宝石<2.3 – Tachyons

+0

@Tachyons是正确的,我已经添加了我的答案的要求。 – Stefan

+0

我使用的是ruby 2.1.3,这不起作用。有没有其他方法可以做到这一点? – Abhishek

1

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

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

我有哈希键与空间和将键转换为符号后工作。

哈希具有字符串键(它返回上插一个错误):

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

转换哈希键符号为我工作:

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.