牛骨文教育服务平台(让学习变的简单)
  • 尽量使用字符串插值(interpolation),而不是字符串连接(concatenation)。

    # 差
    email_with_name = user.name + " <" + user.email + ">"
    
    # 好
    email_with_name = "#{user.name} <#{user.email}>"
    
  • 对于插值表达式, 括号内不应有留白(padded-spacing)。

    # 差
    "From: #{ user.first_name }, #{ user.last_name }"
    
    # 好
    "From: #{user.first_name}, #{user.last_name}"
    
  • 选定一个字符串字面量创建的风格。Ruby 社区认可两种分割,默认用单引号(风格 A)和默认用双引号(风格 B)

    • (风格 A)当你不需要插入特殊符号如  ", 等等时,尽量使用单引号的字符串。

      # 差
      name = "Bozhidar"
      
      # 好
      name = "Bozhidar"
      
    • (风格 B) 用双引号。除非字符串中含有双引号,或者含有你希望抑制的逃逸字符。

      # 差
      name = "Bozhidar"
      
      # 好
      name = "Bozhidar"
      

    有争议的是,第二种风格在 Ruby 社区里更受欢迎一些。但是本指南中字符串采用第一种风格。

  • 不要用 ?x。从 Ruby 1.9 开始, ?x 和 "x" 是等价的(只包括一个字符的字符串)。

    # 差
    char = ?c
    
    # 好
    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
    
      # 差 - 有效,但难看
      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 默认会调用该方法。

    # 差
    message = "This is the #{result.to_s}."
    
    # 好
    message = "This is the #{result}."
    
  • 当你需要建构庞大的数据块(chunk)时,避免使用 String#+ 。 使用 String#<< 来替代。<< 就地改变字符串实例,因此比 String#+ 来得快。String#+ 创造了一堆新的字符串对象。

      # 好也比较快
      html = ""
      html << "<h1>Page title</h1>"
    
      paragraphs.each do |paragraph|
        html << "<p>#{paragraph}</p>"
      end
    
  • 当你可以选择更快速、更专门的替代方法时,不要使用 String#gsub

    url = "http://example.com"
    str = "lisp-case-rules"
    
    # 差
    url.gsub("http://", "https://")
    str.gsub("-", "_")
    
    # 好
    url.sub("http://", "https://")
    str.tr("-", "_")
    
  • heredocs 中的多行文字会保留前缀空白。因此做好如何缩进的规划。

    code = <<-END.gsub(/^s+|/, "")
      |def test
      |  some_method
      |  other_method
      |end
    END
    #=> "def
      some_method
      
    other_method
    end"