Overview

We have the following naming conventions in Ruby concerning method names:

  • my_method=
  • my_method?
  • my_method!

Method names that end with the equals sign

Apparently, these indicate an assignment method (setter). This one is self-explanatory.

Method names that end with question mark

Question mark is added to predicate methods - these are methods that would return either true or false. Common violation of that convention is to use e.g. is_active instead of active?or simply active as name. Another violation is that we return values other than true or false.

It is good to remember that all values in Ruby are truthy except for nil and false.

Method names that end with an exclamation mark

The convention for usage of an exclamation mark (! ) at the end of a method can be defined as follows:

  • We add the character ! at the end of the method name if there are two versions of the method defined - same name and difference of the behaviour. Usually, the “more-dangerous” method receives the exclamation mark whatever dangerous means in the given context.
  • It is not necessary that method with ! at the end mutates an object. Not to mention that there are actually methods like Array#pop that mutate an object.

History

Ruby is influenced by languages like Lisp/Scheme:

Ruby is a language of careful balance. Its creator, Yukihiro “Matz” Matsumoto, blended parts of his favorite languages (Perl, Smalltalk, Eiffel, Ada, and Lisp) to form a new language that balanced functional programming with imperative programming.

In Lisp and Scheme, the exclamation mark (!) is often used in function names to indicate that the function performs a mutation or side effect. This convention helps programmers understand which functions are impure and can change state or have other side effects. This practice was established long before Ruby and influenced many other languages, including Ruby.

This convention was adopted and extended in Ruby’s design philosophy to enhance code readability and expressiveness. In Ruby, the exclamation mark (!) is used to indicate that a method performs a more dangerous or potentially surprising operation compared to its non-bang counterpart.

Conclusion

  • The history of the ? and ! conventions in Ruby is rooted in Matz’s goal to create a language that is intuitive and readable.
  • Do not define bang method if there isn’t a “bangless” version with the same name.
  • Violating this naming convention is called “Prima Donna Method” code smell.

References