淺析Ruby的原始碼布局及其編程風格_ruby專題

來源:互聯網
上載者:User

使用 UTF-8 作為源檔案編碼。

    每個縮排層級使用兩個 spaces (又名軟 tabs). 不要硬 tabs

  # bad - four spaces  def some_method    do_something  end  # good  def some_method   do_something  end

    使用 Unix-風格 分行符號。(*BSD/Solaris/Linux/OSX 使用者被為預設涵蓋,Windows 使用者必須特別小心.)

  •         \n是換行,英文是LineFeed,ASCII碼是0xA。
  •         \r是斷行符號,英文是Carriage Return ,ASCII碼是0xD。
  •         windows下enter是 \n\r,unix下是\n,mac下是\r

        如果你正在使用 Git 你可能會想要添加下面的配置設定來保護你的項目(避免)Windows 蔓延過來的分行符號:

 

  $ git config --global core.autocrlf true

    不用使用 ; 來分割語句和運算式。以此推論 - 一行使用一個運算式

  

 # bad  puts 'foobar'; # superfluous semicolon  puts 'foo'; puts 'bar' # two expression on the same line  # good  puts 'foobar'  puts 'foo'  puts 'bar'  puts 'foo', 'bar' # this applies to puts in particular

    對於沒有內容的類定義,儘可能使用單行類定義形式.

   

 # bad  class FooError < StandardError  end  # okish  class FooError < StandardError; end  # good  FooError = Class.new(StandardError)

    避免單行方法。即便還是會受到一些人的歡迎,這裡還是會有一些古怪的文法用起來很容易犯錯.
    無論如何 - 應該一行不超過一個單行方法.

    

# bad  def too_much; something; something_else; end  # okish - notice that the first ; is required  def no_braces_method; body end  # okish - notice that the second ; is optional  def no_braces_method; body; end  # okish - valid syntax, but no ; make it kind of hard to read  def some_method() body end  # good  def some_method   body  end

    空方法是這個規則的例外。

  # good  def no_op; end

    操作符旁的空格,在逗號,冒號和分號後;在 { 旁和在 } 之前,大多數空格可能對 Ruby 解釋(代碼)無關,但是它的恰當使用是讓代碼變得易讀的關鍵。

  sum = 1 + 2  a, b = 1, 2  1 > 2 ? true : false; puts 'Hi'  [1, 2, 3].each { |e| puts e }

    唯一的例外是當使用指數操作時:

  # bad  e = M * c ** 2  # good  e = M * c**2

    { 和 } 值得額外的澄清,自從它們被用於 塊 和 hash 字面量,以及以運算式的形式嵌入字串。
    對於 hash 字面量兩種風格是可以接受的。

  # good - space after { and before }  { one: 1, two: 2 }  # good - no space after { and before }  {one: 1, two: 2}

    第一種稍微更具可讀性(並且爭議的是一般在 Ruby 社區裡面更受歡迎)。
    第二種可以增加了 塊 和 hash 可視化的差異。
    無論你選哪一種都行 - 但是最好保持一致。

    目前對於嵌入運算式,也有兩個選擇:

  # good - no spaces  "string#{expr}"  # ok - arguably more readable  "string#{ expr }"

    第一種風格極為流行並且通常建議你與之靠攏。第二種,在另一方面,(有爭議)更具可讀性。
    如同 hash - 選取一個風格並且保持一致。

    沒有空格 (, [之後或者 ], )之前。

 

  some(arg).other  [1, 2, 3].length  ! 之後沒有空格 .  # bad  ! something  # good  !something

    when和case 縮排深度一致。我知道很多人會不同意這點,但是它是"The Ruby Programming Language" 和 "Programming Ruby"中公認的風格。

    

# bad  case   when song.name == 'Misty'    puts 'Not again!'   when song.duration > 120    puts 'Too long!'   when Time.now.hour > 21    puts "It's too late"   else    song.play  end  # good  case  when song.name == 'Misty'   puts 'Not again!'  when song.duration > 120   puts 'Too long!'  when Time.now.hour > 21   puts "It's too late"  else   song.play  end  case  when song.name == 'Misty'   puts 'Not again!'  when song.duraton > 120   puts 'Too long!'  when Time.now > 21   puts "It's too late"  else   song.play  end

    當賦值一個條件運算式的結果給一個變數時,保持分支的縮排在同一層。

 

  # bad - pretty convoluted  kind = case year  when 1850..1889 then 'Blues'  when 1890..1909 then 'Ragtime'  when 1910..1929 then 'New Orleans Jazz'  when 1930..1939 then 'Swing'  when 1940..1950 then 'Bebop'  else 'Jazz'  end  result = if some_cond   calc_something  else   calc_something_else  end  # good - it's apparent what's going on  kind = case year      when 1850..1889 then 'Blues'      when 1890..1909 then 'Ragtime'      when 1910..1929 then 'New Orleans Jazz'      when 1930..1939 then 'Swing'      when 1940..1950 then 'Bebop'      else 'Jazz'      end  result = if some_cond        calc_something       else        calc_something_else       end  # good (and a bit more width efficient)  kind =   case year   when 1850..1889 then 'Blues'   when 1890..1909 then 'Ragtime'   when 1910..1929 then 'New Orleans Jazz'   when 1930..1939 then 'Swing'   when 1940..1950 then 'Bebop'   else 'Jazz'   end  result =   if some_cond    calc_something   else    calc_something_else   end

    在方法定義之間使用空行並且一個方法根據邏輯段來隔開。

   

 def some_method   data = initialize(options)   data.manipulate!   data.result  end  def some_methods   result  end

    避免在一個方法調用的最後一個參數有逗號,特別是當參數不在另外一行。

   

 # bad - easier to move/add/remove parameters, but still not preferred  some_method(         size,         count,         color,        )  # bad  some_method(size, count, color, )  # good  some_method(size, count, color)

    當給方法的參數賦預設值時,在 = 兩邊使用空格:

  

 # bad  def some_method(arg1=:default, arg2=nil, arg3=[])   # do something...  end  # good  def some_method(arg1 = :default, arg2 = nil, arg3 = [])   # do something...  end

    雖然幾本 Ruby 書建議用第一個風格,不過第二個風格在實踐中更為常見(並可爭議地可讀性更高一點)。

    避免在不需要的時候使用行繼續符 \ 。實踐中,
    除非用於連接字串, 否則避免在任何情況下使用行繼續符。

 

  # bad  result = 1 - \       2  # good (but still ugly as hell)  result = 1 \       - 2  long_string = 'First part of the long string' \         ' and second part of the long string'

    採用連貫的多行方法鏈式風格。在 Ruby 社區有兩種受歡迎的風格,它們都被認為很好
    - . 開頭(選項 A) 和 尾隨 . (選項 B) 。

        (選項 A) 當一個鏈式方法調用需要在另一行繼續時,將 . 放在第二行。

        

# bad - need to consult first line to understand second line    one.two.three.     four    # good - it's immediately clear what's going on the second line    one.two.three     .four

        (選項 B) 當在另一行繼續一個鏈式方法調用,將 . 放在第一行來識別要繼續的運算式。

     

  # bad - need to read ahead to the second line to know that the chain continues    one.two.three     .four    # good - it's immediately clear that the expression continues beyond the first line    one.two.three.     four

        在這裡可以發現有關這兩個另類風格的優點的討論。

    如果一個方法調用的跨度超過了一行,對齊它們的參數。當參數對齊因為行寬限制而不合適,
    在第一行之後單縮排也是可以接受的。

  

 # starting point (line is too long)  def send_mail(source)   Mailer.deliver(to: 'bob@example.com', from: 'us@example.com', subject: 'Important message', body: source.text)  end  # bad (double indent)  def send_mail(source)   Mailer.deliver(     to: 'bob@example.com',     from: 'us@example.com',     subject: 'Important message',     body: source.text)  end  # good  def send_mail(source)   Mailer.deliver(to: 'bob@example.com',           from: 'us@example.com',           subject: 'Important message',           body: source.text)  end  # good (normal indent)  def send_mail(source)   Mailer.deliver(    to: 'bob@example.com',    from: 'us@example.com',    subject: 'Important message',    body: source.text   )  end

    對齊多行跨度的 array literals 的元素。

   

 # bad - single indent  menu_item = ['Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam',   'Baked beans', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam']  # good  menu_item = [   'Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam',   'Baked beans', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam'  ]  # good  menu_item =   ['Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam',    'Baked beans', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam']

    大數值添加底線來提高它們的可讀性。

  # bad - how many 0s are there?  num = 1000000  # good - much easier to parse for the human brain  num = 1_000_000

    使用 RDoc 以及它的慣例來撰寫 API 文檔。註解區塊及 def 不要用空行隔開。

    每一行限制在 80 個字元內。

    避免行尾空格。

    不要使用區塊注釋。它們不能由空白引導(=begin 必須頂頭開始),並且不如普通注釋容易辨認。

 

  # bad  == begin  comment line  another comment line  == end  # good  # comment line  # another comment line

    在 API 文檔中使用 RDoc和它的公約。不要在注釋代碼塊和def之間加入空行。

    保持每一行少於80字元。

    避免尾隨空格。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.