Ruby中的字符串編寫示例
優(yōu)先使用 字符串插值 來代替 字符串串聯(lián)。
# bad email_with_name = user.name + ' <' + user.email + '>' # good email_with_name = "#{user.name} <#{user.email}>" # good email_with_name = format('%s <%s>', user.name, user.email)
Consider padding string interpolation code with space. It more clearly sets the
code apart from the string.考慮使用空格填充字符串插值。它更明確了除字符串的插值來源。
"#{ user.last_name }, #{ user.first_name }"
Consider padding string interpolation code with space. It more clearly sets the
code apart from the string.
考慮替字符串插值留白。這使插值在字符串里看起來更清楚。
"#{ user.last_name }, #{ user.first_name }"
采用一致的字符串字面量引用風格。這里有在社區(qū)里面受歡迎的兩種風格,它們都被認為非常好 -
默認使用單引號(選項 A)以及雙引號風格(選項 B)。
(Option A) 當你不需要字符串插值或者例如 \t, \n, ' 這樣的特殊符號的
時候優(yōu)先使用單引號引用。
# bad name = "Bozhidar" # good name = 'Bozhidar'
(Option B) Prefer double-quotes unless your string literal
contains " or escape characters you want to suppress.
除非你的字符串字面量包含 " 或者你需要抑制轉(zhuǎn)義字符(escape characters)
優(yōu)先使用雙引號引用。
# bad name = 'Bozhidar' # good name = "Bozhidar"
第二種風格可以說在 Ruby 社區(qū)更受歡迎些。該指南的字符串字面量,無論如何,
與第一種風格對齊。
不要使用 ?x 符號字面量語法。從 Ruby 1.9 開始基本上它是多余的,?x 將會被解釋為 x (只包括一個字符的字符串)。
# bad char = ?c # good char = 'c'
別忘了使用 {} 來圍繞被插入字符串的實例與全局變量。
class Person attr_reader :first_name, :last_name def initialize(first_name, last_name) @first_name = first_name @last_name = last_name end # bad - valid, but awkward def to_s "#@first_name #@last_name" end # good def to_s "#{@first_name} #{@last_name}" end end $global = 0 # bad puts "$global = #$global" # good puts "$global = #{$global}"
在對象插值的時候不要使用 Object#to_s,它將會被自動調(diào)用。
# bad message = "This is the #{result.to_s}." # good message = "This is the #{result}."
操作較大的字符串時, 避免使用 String#+ 做為替代使用 String#<<。就地級聯(lián)字符串塊總是比 String#+ 更快,它創(chuàng)建了多個字符串對象。
# good and also fast html = '' html << '<h1>Page title</h1>' paragraphs.each do |paragraph| html << "<p>#{paragraph}</p>" end
When using heredocs for multi-line strings keep in mind the fact
that they preserve leading whitespace. It's a good practice to
employ some margin based on which to trim the excessive whitespace.
heredocs 中的多行文字會保留前綴空白。因此做好如何縮進的規(guī)劃。這是一個很好的
做法,采用一定的邊幅在此基礎上削減過多的空白。
code = <<-END.gsub(/^\s+\|/, '') |def test | some_method | other_method |end END #=> "def test\n some_method\n other_method\nend\n"