Naming Conventions
Ruby programmers can often guess what a name is before reading its definition. open? answers yes or no. sort! changes something in place. OrderQueue is a class. This is not luck; it is a set of shared habits, and following them makes your Bean Cart code read like everyone else's Ruby.
The rule
snake_case for things, CamelCase for kinds, a final
?or!for warnings.
The core rules:
| What | Style | Bean Cart example |
|---|---|---|
| Variables, methods | snake_case |
cups_sold, daily_total |
| Classes, modules | CamelCase |
CoffeeCart, OrderQueue |
| Constant values | SCREAMING_SNAKE_CASE |
TAX_RATE, MAX_CUPS |
| File names | snake_case.rb |
coffee_cart.rb holds CoffeeCart |
Two punctuation marks are allowed at the end of a method name, and they carry meaning:
- A trailing
?marks a predicate: a method that answers a yes/no question and returnstrueorfalse. Ruby's own examples:empty?,nil?,even?,include?. - A trailing
!marks the "dangerous" version of a method that also exists without it. Usually the!version changes the object itself, while the plain one returns a new object:
name = "bean cart"
name.upcase # => "BEAN CART", name is unchanged
name.upcase! # name itself is now "BEAN CART"
[3, 1, 2].empty? # => falseThe ! does not simply mean "changes things". Plenty of methods change their object without one, such as push or delete. It means "careful: there is a safer twin".
Other habits worth copying:
- Name a method that sets a value with a trailing
=:price=lets you writecart.price = 5. - Avoid
get_andis_prefixes: preferpriceoverget_price, andopen?overis_open. - A leading underscore, as in
_unused, tells readers (and Ruby's warnings) that a variable is deliberately ignored.
The shortcut
Read a name's shape: its first letter and its last character. Capital first letter means a class, module or constant. Ends in ?: expect true or false. Ends in !: expect a safer twin without the !, and possibly changed data.
A blueprint for carts
It is a kind of thing, so it takes CamelCase:
CoffeeCart, stored incoffee_cart.rb.
Drills
Answer fast — trust the rule.
Which is the conventional name for a class?
What should a method named sold_out? return?
After name = "tea" and name.capitalize, what is name?
Which name follows Ruby conventions best?
What does a trailing ! on a method name tell you?
Remember
- snake_case for things, CamelCase for kinds, SCREAMING_SNAKE_CASE for fixed values.
- Read the shape:
?means a yes/no answer;!means a more dangerous twin exists. - Trap: thinking
!simply means "mutates", or writingget_andis_prefixes.
