優先使用 字符串插值 來代替 字符串串聯。
# 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 }"
采用一致的字符串字面量引用風格。這里有在社區里面受歡迎的兩種風格,它們都被認為非常好 -
默認使用單引號(選項 A)以及雙引號風格(選項 B)。
(Option A) 當你不需要字符串插值或者例如 \t, \n, ' 這樣的特殊符號的
時候優先使用單引號引用。
# bad
name = "Bozhidar"
# good
name = 'Bozhidar'
(Option B) Prefer double-quotes unless your string literal
contains " or escape characters you want to suppress.
除非你的字符串字面量包含 " 或者你需要抑制轉義字符(escape characters)
優先使用雙引號引用。
# bad
name = 'Bozhidar'
# good
name = "Bozhidar"
第二種風格可以說在 Ruby 社區更受歡迎些。該指南的字符串字面量,無論如何,
與第一種風格對齊。
不要使用 ?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,它將會被自動調用。
# bad
message = "This is the #{result.to_s}."
# good
message = "This is the #{result}."
操作較大的字符串時, 避免使用 String#+ 做為替代使用 String#。就地級聯字符串塊總是比 String#+ 更快,它創建了多個字符串對象。
# 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 中的多行文字會保留前綴空白。因此做好如何縮進的規劃。這是一個很好的
做法,采用一定的邊幅在此基礎上削減過多的空白。
code = -END.gsub(/^\s+\|/, '')
|def test
| some_method
| other_method
|end
END
#=> "def test\n some_method\n other_method\nend\n"
您可能感興趣的文章:- 詳解Ruby中正則表達式對字符串的匹配和替換操作
- Ruby的字符串與數組求最大值的相關問題討論
- Ruby中操作字符串的一些基本方法
- Ruby中常用的字符串處理函數使用實例
- Ruby簡潔學習筆記(一):字符串、數字、類和對象
- Ruby中創建字符串的一些技巧小結
- Ruby中實現把字符串轉換為類的2種方法
- Ruby中字符串左側補零方法實例
- Ruby字符串、條件、循環、數組、Hash、類基本操作筆記
- Ruby 字符串處理
- Ruby編寫HTML腳本替換小程序的實例分享