2012-12-15 56 views
0

我怎么能存储格式字符串这样红宝石“存储”格式字符串

s = "test with #{value}" 

,这样以后我可以做到这一点

puts s % {:value => 'hello'} 

如果我写的第一件事,它抱怨说,未找到value(确实,我想稍后提供)。如果我使用原始字符串s = 'test with #{value}'它不会插值。

我具体试过这样:

​​

,我得到这个:

KeyError (key{who.sub ' ', '+'} not found): 

回答

5

这仅适用于红宝石1.9+:

s = "test with %{value}" 
puts s % { value: 'hello' } # => test with hello 
+0

喜。谢谢你的答案...我试过了,但它不起作用。你会检查我的编辑?我使用红宝石1.9.3p327 – pistacchio

+1

好吧,你不能在'%{}'中使用ruby代码。它与'#{}'不一样 –

0

镐头http://pragprog.com/book/ruby3/programming-ruby-1-9String#%下称:

如果格式规范包含多个替换,则arg必须是包含要替换的值的数组。

@format_html = "<a href=\"http://boardgamegeek.com/user/%s\">%s</a> receives <a href=\"%s\">%s</a> from <a href=\"http://boardgamegeek.com/user/%s\">%s</a> and sends <a href=\"%s\">%s</a> to <a href=\"http://boardgamegeek.com/user/%s\">%s</a>" 
h = {:who => 'who', 
    :given => ['given1', 'given2'], 
    :from => 'from ', 
    :got => ['got1', 'got2'], 
    :to => 'to  '} 
who, given, from, got, to = h.values 
who_plus = who.gsub(' ', '+') 
got0  = got[0] 
got1  = got[1] 
from_plus = from.gsub(' ', '+') 
given0 = given[0] 
given1 = given[1] 
to_plus = to.gsub(' ', '+') 
puts @format_html % [who_plus, who, got0, got1, from_plus, from, given0, given1, to_plus, to] 

执行:

$ ruby -w t.rb 
<a href="http://boardgamegeek.com/user/who">who</a> receives <a href="got1">got2</a> from <a href="http://boardgamegeek.com/user/from++++">from </a> and sends <a href="given1">given2</a> to <a href="http://boardgamegeek.com/user/to+++++">to  </a>