Ruby"存储"格式字符串

pis*_*hio 0 ruby string

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

s = "test with #{value}"
Run Code Online (Sandbox Code Playgroud)

所以以后我可以这样做

puts s % {:value => 'hello'}
Run Code Online (Sandbox Code Playgroud)

如果我写第一件事,就会抱怨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'}
Run Code Online (Sandbox Code Playgroud)

我明白了

KeyError (key{who.sub ' ', '+'} not found):
Run Code Online (Sandbox Code Playgroud)

Vas*_*ich 5

这仅适用于ruby 1.9+:

s = "test with %{value}"
puts s % { value: 'hello' } # => test with hello
Run Code Online (Sandbox Code Playgroud)