我在ruby中使用模板字符串。例如:
foo = "bar"
"let's go to the #{foo}" #=> let's go to the bar
我有很多带有特殊字符的字符串,偶然发现了%q分隔符技巧,这非常有用。
%q["I don't respect them", he said] #=> "\"I don't respect them\", he said"
不幸的是,它似乎不适用于插值。
catchphrase = 'wubba lubba dub dub'
%[My new catchphrase is "#{catchphrase}"] #=> "My new catchphrase is \"\#{catchphrase}\""
关于如何使插值和%符号很好地发挥作用的任何想法?
答案 0 :(得分:5)
尝试使用%Q
代替%q
。例如:
catchphrase = 'wubba lubba dub dub'
%Q[My new catchphrase is "#{catchphrase}"] #=> "My new catchphrase is \"wubba lubba dub dub\""