Naming
Name identifiers in English. [link]
# bad: identifier using non-ascii characters заплата = 1_000 # bad: identifier is a Bulgarian word, written with Latin letters (instead of Cyrillic) zaplata = 1_000 # good salary = 1_000
Use
snake_case
for symbols, methods and variables. [link]# bad :"some symbol" :SomeSymbol :someSymbol someVar = 5 def someMethod ... end def SomeMethod ... end # good :some_symbol def some_method ... end
Use
CamelCase
for classes and modules. (Keep acronyms like HTTP, RFC, XML uppercase.)Note: The autoloader in Rails expects acronyms to have an initial capital only (
ApiWrapper
instead ofAPIWrapper
), so it makes sense to use that style in Rails code. [link]# bad class Someclass ... end class Some_Class ... end class SomeXml ... end class XmlSomething ... end # good class SomeClass ... end class SomeXML ... end class XMLSomething ... end
Use
snake_case
for naming files, e.g.hello_world.rb
. [link]Use
snake_case
for naming directories, e.g.lib/hello_world/hello_world.rb
. [link]Aim to have just a single class/module per source file. Name the file name as the class/module, but replacing CamelCase with snake_case. [link]
Use
SCREAMING_SNAKE_CASE
for other constants. [link]# bad SomeConst = 5 # good SOME_CONST = 5
The names of predicate methods (methods that return a boolean value) should end in a question mark. (i.e.
Array#empty?
). Methods that don't return a boolean, shouldn't end in a question mark. [link]The names of potentially dangerous methods (i.e. methods that modify
self
or the arguments,exit!
(doesn't run the finalizers likeexit
does), etc.) should end with an exclamation mark if there exists a safe version of that dangerous method.Note: Rails mostly ignores this convention. In Rails related code,
!
is often added to methods that modify the receiver. These method may or may not have a non-modifying version. [link]# bad: there is no matching 'safe' method class Person def update! end end # good class Person def update end end # good class Person def update! end def update end end
Define the non-bang (safe) method in terms of the bang (dangerous) one if possible. [link]
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
When defining binary operators, name the parameter
other
(<<
and[]
are exceptions to the rule, since their semantics are different). [link]def +(other) # body omitted end