03 - Naming
The only real difficulties in programming are cache invalidation and naming things.
-- Phil Karlton
-
# 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.# bad :'some symbol' :SomeSymbol :someSymbol someVar = 5 def someMethod # some code end def SomeMethod # some code end # good :some_symbol def some_method # some code end
Use
CamelCase
for classes and modules. (Keep acronyms like HTTP, RFC, XML uppercase.)# bad class Someclass # some code end class Some_Class # some code end class SomeXml # some code end class XmlSomething # some code end # good class SomeClass # some code end class SomeXML # some code end class XMLSomething # some code end
Use
snake_case
for naming directories, e.g.lib/hello_world/hello_world.rb
.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.
Use
SCREAMING_SNAKE_CASE
for other constants.# 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.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.# 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.
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 using
reduce
with short blocks, name the arguments|a, e|
(accumulator, element).When defining binary operators, name the parameter
other
(<<
and[]
are exceptions to the rule, since their semantics are different).def +(other) # body omitted end