0

如何存储这样的格式字符串

s = "test with #{value}"

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

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

如果我写第一件事,它会抱怨value找不到(真的,我想稍后再提供)。如果我使用原始字符串s = 'test with #{value}',则不会对其进行插值。

我专门尝试了这个:

@format_html = "<a href=\"http://boardgamegeek.com/user/%{who.sub ' ', '+'}\">%{who}</a> receives <a href=\"%{got[0]}\">%{got[1]}</a> from <a href=\"http://boardgamegeek.com/user/%{from.sub ' ', '+'}\">%{from}</a> and sends <a href=\"%{given[0]}\">%{given[1]}</a> to <a href=\"http://boardgamegeek.com/user/%{to.sub ' ', '+'}\">%{to}</a>"
puts @format_html % {:who   => 'who',
                        :given => 'given',
                        :from  => 'from',
                        :got   => 'got',
                        :to    => 'to'}

我明白了:

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

2 回答 2

5

这仅适用于 ruby​​ 1.9+:

s = "test with %{value}"
puts s % { value: 'hello' } # => test with hello
于 2012-12-15T10:16:51.383 回答
0

http://pragprog.com/book/ruby3/programming-ruby-1-9在下面说String#%

如果格式规范包含多个替换,则 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>
于 2012-12-15T12:11:23.010 回答