Ruby中百分号和字面值的使用示例
需要插值与嵌入双引号的单行字符串使用%()(是%Q的简写)。多行字符串,最好用heredocs。
#bad(nointerpolationneeded)
%(<divclass="text">Sometext</div>)
#shouldbe'<divclass="text">Sometext</div>'
#bad(nodouble-quotes)
%(Thisis#{quality}style)
#shouldbe"Thisis#{quality}style"
#bad(multiplelines)
%(<div>\n<spanclass="big">#{exclamation}</span>\n</div>)
#shouldbeaheredoc.
#good(requiresinterpolation,hasquotes,singleline)
%(<tr><tdclass="name">#{name}</td>)
没有'和"的字符串不要使用%q。除非许多字符需要转义,否则普通字符串可读性更好。
#bad
name=%q(BruceWayne)
time=%q(8o'clock)
question=%q("Whatdidyousay?")
#good
name='BruceWayne'
time="8o'clock"
question='"Whatdidyousay?"'
%r的方式只适合于定义包含多个/符号的正则表达式。
#bad %r(\s+) #stillbad %r(^/(.*)$) #shouldbe/^\/(.*)$/ #good %r(^/blog/2011/(.*)$)
除非调用的命令中用到了反引号(这种情况不常见),否则不要用%x。
#bad date=%x(date) #good date=`date` echo=%x(echo`date`)
不要用%s。社区倾向使用:"somestring"来创建含有空白的符号。
用%表示字面量时使用(),%r除外。因为大括号经常出现在正则表达式在很多场景中在很多场景中不太通用的字符例如{作为分割符可能是一个更好的选择,取决于正则式的内容。
#bad
%w[onetwothree]
%q{"Test'sking!",Johnsaid.}
#good
%w(onetwothree)
%q("Test'sking!",Johnsaid.)