• 使用统一的风格创建字符串字面量。在 Ruby 社区中存在两种流行的风格:默认单引号(风格 A)与默认双引号(风格 B)。
    [link]

    • (风格 A) 当你不需要字符串插值或特殊字符(比如 、\n')时,倾向使用单引号。

      1. # 差
      2. name = "Bozhidar"
      3. # 好
      4. name = 'Bozhidar'
    • (风格 B) 除非字符串中包含双引号,或是你希望抑制转义字符,否则倾向使用双引号。

      1. # 差
      2. name = 'Bozhidar'
      3. # 好
      4. name = "Bozhidar"

  • 不要使用 ?x 字面量语法。在 Ruby 1.9 之后,?x'x'(只包含单个字符的字符串)是等价的。
    [link]


  • 不要忘记使用 {} 包裹字符串插值中的实例变量或全局变量。
    [link]

    1. class Person
    2. attr_reader :first_name, :last_name
    3. def initialize(first_name, last_name)
    4. = first_name
    5. @last_name = last_name
    6. end
    7. # 差 - 语法正确,但略显笨拙
    8. def to_s
    9. "# #@last_name"
    10. end
    11. # 好
    12. def to_s
    13. "#{} #{@last_name}"
    14. end
    15. end
    16. $global = 0
    17. # 差
    18. puts "$global = #$global"
    19. # 好
    20. puts "$global = #{$global}"

  • 在字符串插值中,不要显式调用 Object#to_s 方法,Ruby 会自动调用它。
    [link]

    1. # 差
    2. message = "This is the #{result.to_s}."

  • 当存在更快速、更专业的替代方案时,不要使用 String#gsub
    [link]

    1. url = 'http://example.com'
    2. str = 'lisp-case-rules'
    3. # 差
    4. url.gsub('http://', 'https://')
    5. str.gsub('-', '_')
    6. # 好
    7. url.sub('http://', 'https://')
    8. str.tr('-', '_')

  • heredocs 中的多行文本会保留各行的前导空白。因此做好如何缩排的规划。
    [link]

    1. code = <<-END.gsub(/^\s+\|/, '')
    2. |def test
    3. | some_method
    4. | other_method
    5. |end
    6. END
    7. # => "def test\n some_method\n other_method\nend\n"

  • 使用 Ruby 2.3 新增的 <<~ 操作符来缩排 heredocs 中的多行文本。
    [link]