程式设计的真正难题是替事物命名及使缓存失效。
——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