使用统一的风格创建字符串字面量。在 Ruby 社区中存在两种流行的风格:默认单引号(风格 A)与默认双引号(风格 B)。
[link](风格 A) 当你不需要字符串插值或特殊字符(比如 、
\n
、'
)时,倾向使用单引号。# 差
name = "Bozhidar"
# 好
name = 'Bozhidar'
(风格 B) 除非字符串中包含双引号,或是你希望抑制转义字符,否则倾向使用双引号。
# 差
name = 'Bozhidar'
# 好
name = "Bozhidar"
不要使用?x
字面量语法。在 Ruby 1.9 之后,?x
与'x'
(只包含单个字符的字符串)是等价的。
[link]
不要忘记使用{}
包裹字符串插值中的实例变量或全局变量。
[link]class Person
attr_reader :first_name, :last_name
def initialize(first_name, last_name)
= first_name
@last_name = last_name
end
# 差 - 语法正确,但略显笨拙
def to_s
"# #@last_name"
end
# 好
def to_s
"#{} #{@last_name}"
end
end
$global = 0
# 差
puts "$global = #$global"
# 好
puts "$global = #{$global}"
在字符串插值中,不要显式调用Object#to_s
方法,Ruby 会自动调用它。
[link]# 差
message = "This is the #{result.to_s}."
当存在更快速、更专业的替代方案时,不要使用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]