使用 :: 引用常量(包括類和模塊)和構造器 (比如 Array() 或者 Nokogiri::HTML())。
永遠不要使用 :: 來調用方法。
# bad SomeClass::some_method some_object::some_method # good SomeClass.some_method some_object.some_method SomeModule::SomeClass::SOME_CONST SomeModule::SomeClass()
使用括號將def的參數括起來。當方法不接收任何參數的時候忽略括號。
# bad def some_method() # body omitted end # good def some_method # body omitted end # bad def some_method_with_arguments arg1, arg2 # body omitted end # good def some_method_with_arguments(arg1, arg2) # body omitted end
從來不要使用 for, 除非你知道使用它的準確原因。大多數時候迭代器都可以用來替for。for 是由一組 each 實現的 (因此你正間接添加了一級),但是有一個小道道 - for并不包含一個新的 scope (不像 each)并且在它的塊中定義的變量在外面也是可以訪問的。
arr = [1, 2, 3] # bad for elem in arr do puts elem end # note that elem is accessible outside of the for loop elem #=> 3 # good arr.each { |elem| puts elem } # elem is not accessible outside each's block elem #=> NameError: undefined local variable or method `elem'
在多行的 if/unless 中堅決不要使用 then。
# bad if some_condition then # body omitted end # good if some_condition # body omitted end
在多行的 if/unless 總是把條件放在與 if/unless 的同一行。
# bad if some_condition do_something do_something_else end # good if some_condition do_something do_something_else end
喜歡三元操作運算(?:)超過if/then/else/end結構。
它更加普遍而且明顯的更加簡潔。
# bad result = if some_condition then something else something_else end # good result = some_condition ? something : something_else
使用一個表達式在三元操作運算的每一個分支下面只使用一個表達式。也就是說三元操作符不要被嵌套。在這樣的情形中寧可使用 if/else。
# bad some_condition ? (nested_condition ? nested_something : nested_something_else) : something_else # good if some_condition nested_condition ? nested_something : nested_something_else else something_else end
不要使用 if x: ... - 它在Ruby 1.9中已經移除。使用三元操作運算代替。
# bad result = if some_condition then something else something_else end # good result = some_condition ? something : something_else
新聞熱點
疑難解答