你可以使用带插值的字符串的ruby百分比表示法吗?

wil*_*des 3 ruby string interpolation

我在ruby中使用模板字符串.例:

foo = "bar"
"let's go to the #{foo}" #=> let's go to the bar
Run Code Online (Sandbox Code Playgroud)

我有很多带有特殊字符的字符串,偶然发现了%q分隔符技巧,它非常有用.

%q["I don't respect them", he said] #=> "\"I don't respect them\", he said"
Run Code Online (Sandbox Code Playgroud)

不幸的是,它似乎不适用于插值.

catchphrase = 'wubba lubba dub dub'
%[My new catchphrase is "#{catchphrase}"] #=> "My new catchphrase is \"\#{catchphrase}\""
Run Code Online (Sandbox Code Playgroud)

关于如何使插值和%符号很好地发挥作用的任何想法?

Jik*_*ose 5

尝试%Q而不是%q.例如:

catchphrase = 'wubba lubba dub dub'
%Q[My new catchphrase is "#{catchphrase}"] #=> "My new catchphrase is \"wubba lubba dub dub\""
Run Code Online (Sandbox Code Playgroud)