> 程式設計的真正難題是替事物命名及使緩存失效。
> ——Phil Karlton
* 標識符用英語命名。
~~~
# 差 - 變量名用非ascii字符
заплата = 1_000
# 差 - 變量名用帶有拉丁文的保加利亞語寫成。
zaplata = 1_000
# 好
salary = 1_000
~~~
* 符號、方法與變量使用蛇底式小寫(snake_case)。
~~~
# 差
:'some symbol'
:SomeSymbol
:someSymbol
someVar = 5
def someMethod
...
end
def SomeMethod
...
end
# 好
:some_symbol
def some_method
...
end
~~~
* 類別與模組使用駝峰式大小寫(CamelCase)。(保留類似 HTTP、RFC、XML 這種縮寫為大寫。)
~~~
# 差
class Someclass
...
end
class Some_Class
...
end
class SomeXml
...
end
# 好
class SomeClass
...
end
class SomeXML
...
end
~~~
* 文件名用蛇底式小寫,如?`hello_world.rb`。
* 目錄名用蛇底式小寫,如?`lib/hello_world/hello_world.rb`。
* 每個類/模塊都在單獨的文件,文件名用蛇底式小寫而不是駝峰式大小寫。
* 其他常數使用尖叫蛇底式大寫(SCREAMING_SNAKE_CASE)。
~~~
# 差
SomeConst = 5
# 好
SOME_CONST = 5
~~~
* 判斷式方法的名字(返回布爾值的方法)應以問號結尾。 (例如:?`Array#empty?`?)。不返回布爾值的方法不應用問號結尾。
* 有潛在**危險性**的方法,若此**危險**方法有安全版本存在時,應以安全版本名加上驚嘆號結尾(例如:改動?`self`?或參數、?`exit!`?(不會向?`exit`?那樣運行 finalizers), 等等方法)。
* 如果存在潛在的**危險**方法(即修改?`self`?或者參數的方法,不像?`exit`?那樣運行 finalizers 的?`exit!`,等等)的安全版本,那么?_危險_?方法的名字應該以驚嘆號結尾。
~~~
# 不好 - 沒有對應的安全方法
class Person
def update!
end
end
# 好
class Person
def update
end
end
# 好
class Person
def update!
end
def update
end
end
~~~
* 如果可能的話,根據危險方法(bang)來定義對應的安全方法(non-bang)。
~~~
class Array
def flatten_once!
res = []
each do |e|
[*e].each { |f| res << f }
end
replace(res)
end
def flatten_once
dup.flatten_once!
end
end
~~~
* 在簡短區塊中使用?`reduce`?時,把參數命名為?`|a, e|`?(累加器(`accumulator`),元素(`element`))
* 在定義二元操作符時,把參數命名為?`other`?(`<<`?與?`[]`?是這條規則的例外,因為它們的語義不同)。
~~~
def +(other)
# body omitted
end
~~~