Names are the documentation you cannot skip. Ruby has strong community conventions for naming, and following them means other Rubyists can read your code without a glossary.
Casing
| Kind | Convention | Example |
|---|---|---|
| Methods and variables | snake_case | order_total |
| Classes and modules | CamelCase | InvoiceMailer |
| Constants | SCREAMING_SNAKE_CASE | MAX_RETRIES |
| Files and directories | snake_case | invoice_mailer.rb |
Keep acronyms upper case in class names, for example HTTPClient or XMLParser, unless your autoloader expects otherwise, and then be consistent.
Predicate methods
A method that returns a boolean ends with a question mark and does not start with is_.
# Avoid
def is_active
status == "active"
end
# Prefer
def active?
status == "active"
end
Bang methods
A trailing exclamation mark signals that a method is the more dangerous version of a safer method with the same name. It usually mutates the receiver or raises instead of returning false. Only use a bang when a non bang counterpart exists.
name.strip # returns a new string
name.strip! # modifies name in place
user.save # returns true or false
user.save! # raises on failure
Setters and getters
Do not prefix readers with get_ or writers with set_. Ruby already has attr_reader and name= style writers.
class Account
attr_reader :balance
def balance=(amount)
raise ArgumentError, "negative balance" if amount.negative?
@balance = amount
end
end
Choosing good names
- Name things by what they mean in the domain, not by their type:
overdue_invoicesbeatsinvoice_array. - Prefer full words to abbreviations.
customeris clearer thancust. - Use a single letter only for very short blocks or well known conventions such as
efor an exception. - Prefix unused block parameters with an underscore, such as
_index, so readers and linters know they are intentional. - Name a method by its result when it returns a value (
total) and by its action when it performs one (send_reminder).