需要插值与嵌入双引号的单行字符串使用
%()
(是%Q
的简写)。多行字符串,最好用 heredocs 。# 差(不需要插值) %(<div class="text">Some text</div>) # 应该使用 "<div class="text">Some text</div>" # 差(没有双引号) %(This is #{quality} style) # 应该使用 "This is #{quality} style" # 差(多行) %(<div> <span class="big">#{exclamation}</span> </div>) # 应该是一个 heredoc # 好(需要插值、有双引号以及单行) %(<tr><td class="name">#{name}</td>)
没有
"
和"
的字符串不要使用%q
。除非需要插值,否则普通字符串可读性更好。# 差 name = %q(Bruce Wayne) time = %q(8 o"clock) question = %q("What did you say?") # 好 name = "Bruce Wayne" time = "8 o"clock" question = ""What did you say?""
只有正则表达式要匹配多于一个的
/
字元时,使用%r
。# 差 %r{s+} # 好 %r{^/(.*)$} %r{^/blog/2011/(.*)$}
除非调用的命令中用到了反引号(这种情况不常见),否则不要用
%x
。# 差 date = %x(date) # 好 date = `date` echo = %x(echo `date`)
不要用
%s
。社区倾向使用:"some string"
来创建含有空白的符号。用
%
表示字面量时使用()
,%r
除外。因为(
在正则中比较常用。# 差 %w[one two three] %q{"Test"s king!", John said.} # 好 %w(one tho three) %q("Test"s king!", John said.)