優先使用 字符串插值 來代替 字符串串聯。
# 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}"
新聞熱點
疑難解答