使用 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 字面量,以及以表達式的形式嵌入字符串。
新聞熱點
疑難解答