Naming Conventions
Ruby uses snake_case for variables and methods, CamelCase for classes and modules, SCREAMING_SNAKE_CASE for constant values, a trailing ? for yes/no methods and a trailing ! for the more dangerous twin of a method.
Use names that communicate value roles and conventional method behavior.
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.