字符串
字符串
- 倾向使用字符串插值或字符串格式化,而不是字符串拼接。
[link]
## 差
email_with_name = user.name + ' <' + user.email + '>'
## 好
email_with_name = "#{user.name} <#{user.email}>"
## 好
email_with_name = format('%s <%s>', user.name, user.email)
-
使用统一的风格创建字符串字面量。在 Ruby 社区中存在两种流行的风格:默认单引号(风格 A)与默认双引号(风格 B)。
[link]- (风格 A) 当你不需要字符串插值或特殊字符(比如
\t、\n、')时,倾向使用单引号。
- (风格 A) 当你不需要字符串插值或特殊字符(比如
## 差
name = "Bozhidar"
## 好
name = 'Bozhidar'
* **(风格 B)** 除非字符串中包含双引号,或是你希望抑制转义字符,否则倾向使用双引号。
## 差
name = 'Bozhidar'
## 好
name = "Bozhidar"
本指南使用第一种风格。
- 不要使用
?x字面量语法。在 Ruby 1.9 之后,?x与'x'(只包含单个字符的字符串)是等价的。
[link]
## 差
char = ?c
## 好
char = 'c'
- 不要忘记使用
{}包裹字符串插值中的实例变量或全局变量。
[link]
class Person
attr_reader :first_name, :last_name
def initialize(first_name, last_name)
@first_name = first_name
@last_name = last_name
end
# 差 - 语法正确,但略显笨拙
def to_s
"#@first_name #@last_name"
end
# 好
def to_s
"#{@first_name} #{@last_name}"
end
end
$global = 0
## 差
puts "$global = #$global"
## 好
puts "$global = #{$global}"
- 在字符串插值中,不要显式调用
Object#to_s方法,Ruby 会自动调用它。
[link]
## 差
message = "This is the #{result.to_s}."
## 好
message = "This is the #{result}."
- 当你需要构造巨大的数据块时,避免使用
String#+,使用String#<<来替代。String#<<通过修改原始对象进行拼接工作,其比String#+效率更高,因为后者需要产生一堆新的字符串对象。
[link]
## 差
html = ''
html += '<h1>Page title</h1>'
paragraphs.each do |paragraph|
html += "<p>#{paragraph}</p>"
end
## 好 - 并且效率更高
html = ''
html << '<h1>Page title</h1>'
paragraphs.each do |paragraph|
html << "<p>#{paragraph}</p>"
end
- 当存在更快速、更专业的替代方案时,不要使用
String#gsub。
[link]
url = 'http://example.com'
str = 'lisp-case-rules'
# 差
url.gsub('http://', 'https://')
str.gsub('-', '_')
# 好
url.sub('http://', 'https://')
str.tr('-', '_')
- heredocs 中的多行文本会保留各行的前导空白。因此做好如何缩排的规划。
[link]
code = <<-END.gsub(/^\s+\|/, '')
|def test
| some_method
| other_method
|end
END
## => "def test\n some_method\n other_method\nend\n"
- 使用 Ruby 2.3 新增的
<<~操作符来缩排 heredocs 中的多行文本。
[link]
## 差 - 使用 Powerpack 程序库的 String#strip_margin
code = <<-END.strip_margin('|')
|def test
| some_method
| other_method
|end
END
## 差
code = <<-END
def test
some_method
other_method
end
END
## 好
code = <<~END
def test
some_method
other_method
end
END
